I'm trying to use the 3D touch force value to change the volume of my AVAudioUnitSampler when a button is pressed depending on how much force is used.
This is my current code to get the force value
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
print(touch.force)
}
}
The problem is that sometimes when I press really hard on my phone (using iPhone 7 plus as physical device) I'm getting 0.0. Sometimes I'll get something greater than 0.0 but it's a problem when I press really hard and get 0.0.
Is my approach to what I'm trying accomplish a good way to do this or is there a better way?
Its generally easier to use a gesture recognizer, but you can still use the UIResponder touch methods; however you are using the wrong one. touchesBegan
is only going to give you the force at the beginning of the touch when the force is very likely to be 0 or close to it. You need to get updates throughout the whole touch so you want touchesMoved
. Of course you then have to decide if the touch has moved too much or if just the pressure has changed, which is why its easier to use UILongPressGestureRecognizer
; it does this for you.