Viktor GidlöfViktor GidlöfViktor GidlöfViktor GidlöfViktor Gidlöf
  • Photography
  • Projects
  • Timeline
  • Resume
  • Buy me a coffee
  • Photography
  • Projects
  • Timeline
  • Resume
  • Buy me a coffee

A Haptic Feedback Engine in Swift 5

July 16, 2021 VG
iOS Development

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:

  1. Start by importing CoreHaptics
  2. Define a private property called engine of type CHHapticEngine
  3. Define an optional private lazy var called player of type CHHapticPatternPlayer
  4. Check if we could create an engine by unwrapping the engine property otherwise return nil
  5. Create an CHHapticEvent with event type hapticTransient. Haptic transient is a brief impulse occurring at a specific point in time, like the feedback from toggling a switch.
  6. Next, create a CHHapticPattern. The pattern is initialized with and array of events that make up the haptic pattern.
  7. And lastly from the pattern we create the player player by calling .makePlayer(with:) on the engine
  8. Create a static constant called default. This will make the haptic engine class a shared singleton instance.
  9. 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.
  10. 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.

Copyright © 2023 Viktor Gidlöf
  • Photography
  • Projects
  • Timeline
  • Resume
  • Buy me a coffee