vibration

UIImpactFeedbackGenerator is Not Working? UIKit - Xcode 13.4.1 - Swift 5


I want to generate vibration when I press the button but I get no results.

Helper class I created to manage vibrations:

import Foundation
import UIKit

final class HapticsManager{
    static let shared = HapticsManager()
    
    private init(){}
    
    public func selectionVibrate(){
        DispatchQueue.main.async {
            let selectionImpactGenerator = UIImpactFeedbackGenerator()
            selectionImpactGenerator.prepare()
            selectionImpactGenerator.impactOccurred()
        }
    }
    
    public func haptic(for type: UIImpactFeedbackGenerator.FeedbackStyle){
        DispatchQueue.main.async {
            let notificationGenerator = UIImpactFeedbackGenerator()
            notificationGenerator.prepare()
            notificationGenerator.impactOccurred()
        }
    }
}

in ViewDidLoad()

  override func viewDidLoad() {
        super.viewDidLoad()
        HapticsManager.shared.selectionVibrate()
        addTargets()
        setStartGradientView()
        showLayout()
    }

Function of button with click target added:

    @objc fileprivate func setButtonClicked(){
        HapticsManager.shared.haptic(for: .heavy)
    }

I tried many methods but no result.

Thanks...


Solution

  • There is no problem about your code but needs some additional information. You need to check if device hardware is support for CHHapticEngine like that;

    public func haptic(for type: UIImpactFeedbackGenerator.FeedbackStyle) {
        if CHHapticEngine.capabilitiesForHardware().supportsHaptics {
            let notificationGenerator = UIImpactFeedbackGenerator()
            notificationGenerator.prepare()
            notificationGenerator.impactOccurred()
        } else {
            AudioServicesPlaySystemSound(1520)
        }
    }