A Haptic Feedback Engine in Swift 5
iOS 13 provides a very versatile way to use the taptic engine in modern iPhones. In this article I will show you how we can create a simple haptic engine to use in our apps for the times when we want to provide that sweet haptic feedback to enhance the user experience. We are gonna create a default haptic engine we can call like this:
HapticEngine.default.start()
Here is the code:
// 1 import CoreHaptics final class HapticEngine { // 2 private let engine = try? CHHapticEngine() // 3 private lazy var player: CHHapticPatternPlayer? = { do { // 4 guard let engine = engine else { return nil } // 5 let event = CHHapticEvent(eventType: .hapticTransient, parameters: [], relativeTime: 0) // 6 let pattern = try CHHapticPattern(events: [event], parameters: []) // 7 let player = try engine.makePlayer(with: pattern) return player } catch { return nil } }() // 8 static let `default` = HapticEngine() // 9 private init() { try? engine?.start() } // 10 func start() { try? player?.start(atTime: 0.0) } }
Okey, lets break the code down:
- Start by importing
CoreHaptics
- Define a private property called
engine
of typeCHHapticEngine
- Define an optional private lazy var called
player
of typeCHHapticPatternPlayer
- Check if we could create an engine by unwrapping the
engine
property otherwise returnnil
- Create an
CHHapticEvent
with event typehapticTransient
. Haptic transient is a brief impulse occurring at a specific point in time, like the feedback from toggling a switch. - Next, create a
CHHapticPattern
. The pattern is initialized with and array of events that make up the haptic pattern. - And lastly from the pattern we create the player player by calling
.makePlayer(with:)
on the engine - Create a static constant called
default
. This will make the haptic engine class a shared singleton instance. - Create a private initializer that tries to start the haptic engine. By making the initializer private we make sure no one can call it by mistake.
- Finally we define a function called
start()
that calls.start(atTime: 0.0)
on the player. This will make the taptic engine in the device.
Now we can call the haptic engine like the sample above anywhere in our code and have the taptic engine run to add that little extra spice in our apps.