CHHapticEngine not generating haptic feedback nor throws error?

98 views Asked by At

I am trying to generate haptic feedback in an iOS application. I am doing so by using CoreHaptics.

My code to do this is as follows:

do {
        let engine = try CHHapticEngine()
        try engine.start()
        
        let hapticPattern = try CHHapticPattern(events: [
            CHHapticEvent(eventType: .hapticTransient, parameters: [
                CHHapticEventParameter(parameterID: .hapticSharpness, value: 1.0),
                CHHapticEventParameter(parameterID: .hapticIntensity, value: 1.0)
            ], relativeTime: CHHapticTimeImmediate)
        ], parameters: [])
        
       let player = try engine.makePlayer(with: hapticPattern)
       try player.start(atTime: 0)
    }
    catch {
        print("Error starting engine: \(error)")
    }

However running this code both directly in the viewDidLoad() method and an @IBAction with a UIButton to trigger it, does not result in any haptics playing.

The code doesn't throw any error either. Not in the catch statement or anywhere else.

I'm testing this on an iPhone 15 Pro. Both with silent mode on and off.

What am I doing wrong here?

1

There are 1 answers

1
matt On BEST ANSWER

The problem is that your engine and player are local variables so they go out of existence when the surrounding function finishes — which is before the haptic even has a chance to play. Lift them up so that each is a property of the surrounding view controller and thus gains long life.