1

I am trying to use UIImpactFeedbackGenerator in a AVCaptureSession. I have

AVAudioSession.sharedInstance().setAllowHapticsAndSystemSoundsDuringRecording(true)

to allow haptic feedback while in a session (iOS 13 only).

However, the feedback is always delayed by a half-second or so.

Here is the code that triggers the event

@IBAction func doubleTapGesture(_ sender: UITapGestureRecognizer) {
    if #available(iOS 13.0, *) {
        DispatchQueue.main.async {
            self.UIImpactHapticFeedback!.impactOccurred()
        }
    }
    self.switchCamera
}

I set up the UIImpactHapticFeedback in my viewDidLoad that also prepares the instance.

I believe it has to do with the switching camera action because the haptic feedback will not happen until after the switching camera action is done.

Can someone help me get the haptic feedback to be instant?

aaaav
  • 151
  • 9

2 Answers2

1

Delete

DispatchQueue.main.async

You are already on the main queue so this line is just delaying you until after the call to switchCamera.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • I originally did not have this but removing it does not noticeably remove the delay of the impact. However, thanks for pointing out that oversight. – aaaav Jul 20 '21 at 21:35
1

So I just found out how to fix this. Since apple notes in their guidelines "Note that calling these methods does not play haptics directly. Instead, it informs the system of the event.", I am guessing that it waits until the camera switch is done to trigger the haptic feedback.

A fix for this is just to put in this delay so the system calls this event relatively immediately.

@IBAction func doubleTapGesture(_ sender: UITapGestureRecognizer) {
        if #available(iOS 13.0, *) {
                self.UIImpactHapticFeedback!.impactOccurred()
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1)
                    {
                        self.switchCamera()
                    }
            }
    }
aaaav
  • 151
  • 9
  • Yep, that's basically what I was getting at. Instead of saying switchCamera and wait for it and then impactOccurred, you want to say impactOccurred and wait for it and then switchCamera. – matt Jul 20 '21 at 22:19