iosswiftxcodehaptic-feedback

Deinit UIImpactFeedbackGenerator


I init a UIImpactFeedbackGenerator with a timer with TimeInterval=1.0. After some seconds, I call the deinitHapticFeedback(), as described below and navigate to the next view controller, but the feedback doesn't stop and keeps occurring for about ten seconds after the new VC appears.

(Also, I tried calling deinitHapticFeedback() in viewWillDisappear(_ animated: Bool), but the same thing happens.)

Do you have any idea for a more optimal deinit function for a UIFeedbackGenerator ?

private var feedbackGenerator: UIImpactFeedbackGenerator? = nil

private func generateHapticFeedback() {
    feedbackGenerator = UIImpactFeedbackGenerator(style: .medium)
    feedbackGenerator?.prepare()
    DispatchQueue.main.async {
        self.feedbackGenerator?.impactOccurred()
    }
}

private func deinitHapticFeedback() {
    feedbackGenerator = nil
}

Thanks in advance! 🙌


Solution

  • You are creating a new UIImpactFeedbackGenerator every time generateHapticFeedback method is called. So even if you set feedbackGenerator to nil, a new object will be created at this line feedbackGenerator = UIImpactFeedbackGenerator(style: .medium).

    Instead of setting feedbackGenerator to nil you have invalidate your timer. If you are using Timer class to schedule timer you can call invalidate method like this timer.invalidate().

    private func deinitHapticFeedback() {
        timer.invalidate() // invalidate timer
    }
    

    You can also restart the timer as well when view controller appears again (if required).