What is Core Haptics

The Core Haptics framework on the iOS platform provides advanced tactile feedback capabilities, allowing developers to create complex and detailed tactile experiences. This is very useful in games, health apps, and other apps that require physical feedback.

Core idea

  • Haptic Engine : Haptic engine, manages the playback of tactile feedback.
  • Pattern : A tactile pattern, consisting of a series of tactile events.
  • Event : Haptic event, which defines the specific behavior of haptic feedback.

1. Check device support

import CoreHaptics

func supportsHaptics() -> Bool {
    return CHHapticEngine.capabilitiesForHardware().supportsHaptics
}

2. Create Haptic Engine

Create and configure a haptic engine.

import CoreHaptics

var hapticEngine: CHHapticEngine?

func createHapticEngine() {
    do {
        hapticEngine = try CHHapticEngine()
        try hapticEngine?.start()
    } catch let error {
        print("Haptic Engine Creation Error: \(error)")
    }
}

3. Define tactile patterns

Use CHHapticEventand CHHapticPatternto define haptic patterns.

func createHapticPattern() -> CHHapticPattern? {
    let event1 = CHHapticEvent(eventType: .hapticContinuous,
                               parameters: [
                                 CHHapticEventParameter(parameterID: .hapticIntensity, value: 1.0),
                                 CHHapticEventParameter(parameterID: .hapticSharpness, value: 1.0)
                               ],
                               relativeTime: 0,
                               duration: 1.0)

    do {
        let pattern = try CHHapticPattern(events: [event1], parameters: [])
        return pattern
    } catch let error {
        print("Haptic Pattern Creation Error: \(error)")
        return nil
    }
}

4. Play tactile mode

Load the defined haptic pattern into the haptic engine and play it.

func playHapticPattern() {
    guard supportsHaptics() else { return }

    do {
        let pattern = createHapticPattern()
        let player = try hapticEngine?.makePlayer(with: pattern!)
        try player?.start(atTime: CHHapticTimeImmediate)
    } catch let error {
        print("Haptic Playback Error: \(error)")
    }
}

Sample code integration

The complete sample code is as follows:

import CoreHaptics
import UIKit

class ViewController: UIViewController {
    var hapticEngine: CHHapticEngine?

    override func viewDidLoad() {
        super.viewDidLoad()
        createHapticEngine()
        playHapticPattern()
    }

    func supportsHaptics() -> Bool {
        return CHHapticEngine.capabilitiesForHardware().supportsHaptics
    }

    func createHapticEngine() {
        guard supportsHaptics() else { return }

        do {
            hapticEngine = try CHHapticEngine()
            try hapticEngine?.start()
        } catch let error {
            print("Haptic Engine Creation Error: \(error)")
        }
    }

    func createHapticPattern() -> CHHapticPattern? {
        let event1 = CHHapticEvent(eventType: .hapticContinuous,
                                   parameters: [
                                     CHHapticEventParameter(parameterID: .hapticIntensity, value: 1.0),
                                     CHHapticEventParameter(parameterID: .hapticSharpness, value: 1.0)
                                   ],
                                   relativeTime: 0,
                                   duration: 1.0)

        do {
            let pattern = try CHHapticPattern(events: [event1], parameters: [])
            return pattern
        } catch let error {
            print("Haptic Pattern Creation Error: \(error)")
            return nil
        }
    }

    func playHapticPattern() {
        guard supportsHaptics() else { return }

        do {
            let pattern = createHapticPattern()
            let player = try hapticEngine?.makePlayer(with: pattern!)
            try player?.start(atTime: CHHapticTimeImmediate)
        } catch let error {
            print("Haptic Playback Error: \(error)")
        }
    }
}

My confusion and answers in actual use

CHHapticEvent

CHHapticEvent.EventType

.hapticContinuous:
  • Description : Creates a persistent haptic event.
  • Usage : For tactile feedback that needs to be felt over a period of time, such as engine vibrations or continuous vibration patterns.
  • Example :
let hapticEvent = CHHapticEvent(eventType: .hapticContinuous,
                                parameters: [],
                                relativeTime: 0,
                                duration: 1.0) // 
.hapticTransient:
  • Description : Creates a momentary haptic event.
  • Purpose : For short, rapid tactile feedback, such as the feeling of a click or tap.
  • Example :
let hapticEvent = CHHapticEvent(eventType: .hapticTransient,
                                parameters: [],
                                relativeTime: 0)
.audioContinuous:
  • Description : Creates a continuous audio event.
  • Usage : For audio that needs to play continuously over a period of time, such as background sound effects or continuous audio warnings.
  • Example :
let audioEvent = CHHapticEvent(eventType: .audioContinuous,
                               parameters: [],
                               relativeTime: 0,
                               duration: 1.0) //
.audioCustom:
  • Description : Create a custom audio event.
  • Purpose : Used to play custom audio files.
  • Example :
// 
let audioURL = URL(fileURLWithPath: "path/to/audio/file")
let audioEvent = CHHapticEvent(eventType: .audioCustom,
                               parameters: [],
                               relativeTime: 0,
                               duration: 1.0) // 
// 

CHHapticEventParameter

.hapticIntensity:

Haptic intensity: Its optional range is 0 to 1.0. It controls the intensity of the phone’s haptic events.

.hapticSharpness:

Tactile sensitivity: Its optional range is 0 to 1.0. It controls the frequency of tactile events on the phone.

other:

In addition to these two commonly used parameters, there are other parameter controls. Since I have not come into contact with them in business, I have not studied them in depth.

relativeTime

Used to control the relative start time of the touch event. Simply put, it means how many seconds to delay the execution of the touch event.

duration

Haptic event response duration.

CHHapticPatternPlayer

Through let player = try hapticEngine?.makePlayer(with: pattern!), you can get an CHHapticPatternPlayerobject, which is a basic pattern player used to play simple tactile patterns.

CHHapticAdvancedPatternPlayer

CHHapticAdvancedPatternPlayeris CHHapticPatternPlayeran advanced version of , providing more control features and is suitable for complex tactile patterns that require fine control.

/// 
   func playHapticPattern(_ pattern: CHHapticPattern, completionHandler: @escaping ((any Error)?) -> Void) {
       createHapticEngine()
       guard supportsHaptics() else { return }
       do {
           player = try hapticEngine?.makeAdvancedPlayer(with: pattern)
           try player?.start(atTime: CHHapticTimeImmediate)
           player?.completionHandler = completionHandler
       } catch let error {
           print(error)
       }
   }

In this way, we can get an event callback in the touch event, and do the remaining logical operations after the event ends.

Core Haptics usage scenarios in medical research

1. Rehabilitation

  • Physical rehabilitation : Using tactile feedback to guide patients in correct movements helps them regain muscle strength and coordination.
  • Neurorehabilitation : Providing targeted tactile stimulation to patients who have suffered a stroke or brain injury to help reconnect the brain to the body.
  • Surgical rehabilitation : During the postoperative rehabilitation process, tactile feedback is used to help patients gradually restore fine motor skills in their hands.

2. Surgical Training

  • Simulated surgery : Simulating real surgical environments through tactile feedback helps surgeons practice complex surgeries in a risk-free environment.
  • Skill Assessment : Use tactile feedback to assess a surgeon’s skill level to ensure they have the necessary precision and sensitivity.

3. Pain management

  • Distraction : Distract the patient’s attention from the pain through specific tactile stimulation, reducing the perception of pain.
  • Pain Assessment : Use haptic feedback systems to objectively assess a patient’s pain level, helping to develop more effective pain management plans.

4. Psychotherapy

  • Anxiety and Stress Management : Helps patients relax and reduce anxiety and stress through specific touch patterns.
  • Emotional regulation : Using tactile feedback to assist in emotional regulation helps patients better control their mood swings.

5. Assistance for the visually or hearing impaired

  • Tactile Alternatives : Providing tactile alternatives to people with visual or hearing impairments to help them perceive and interact with their environment.
  • Navigation assistance : Provides navigation assistance through a tactile feedback system to help the visually impaired move in complex environments.

6. Surgical assistance

  • Minimally invasive surgery : In minimally invasive surgery, tactile feedback is used to provide real-time position and contact information of surgical tools to improve surgical accuracy.
  • Remote Surgery : In remote surgery, tactile feedback can help surgeons better sense the interaction between surgical tools and tissue.

7. Diagnostic Tools

  • Tactile diagnosis : The tactile feedback system can be used to simulate different lesions and tissue conditions to help doctors conduct diagnostic training in a virtual environment.
  • Early detection : Use tactile feedback to assist in early lesion detection and improve the accuracy and timeliness of diagnosis.

8. Biofeedback

  • Real-time feedback : In biofeedback therapy, tactile feedback is used to provide patients with real-time information about their physical state, helping them adjust and optimize their physiological responses.
  • Autonomic nervous system training : Tactile feedback is used to train patients to regulate heart rate, breathing, and other autonomic nervous system functions.

Example Application

  • Rehabilitation Robot : Using tactile feedback to help patients with fine hand rehabilitation training.
  • Virtual Reality Therapy : Combined with virtual reality technology, it provides a more realistic treatment experience through tactile feedback.
  • Smart wearable devices : Smart wearable devices equipped with tactile feedback function provide real-time health monitoring and feedback

Insights

Finally, I would like to share some of my own experiences.

In the process of cooperating with the company’s medical team and algorithm team in research, I deeply realized the true strength of Apple as the world’s most valuable company. Apple is not only a leader in the field of consumer electronics, but also has in-depth research and layout in the fields of medicine and algorithm research that we don’t usually come into contact with. This makes me understand more clearly that Apple’s success is by no means accidental, but stems from its meticulous cultivation and innovation drive in various fields. This comprehensive and in-depth research and investment further consolidates Apple’s leadership in the global technology industry.

Leave a Reply

Your email address will not be published. Required fields are marked *