Swift version: 5.6
Modern iPhones have extremely sensitive haptic engines inside, allowing us precise control over taps and vibrations, and even mixing effects – see “How to play custom vibrations using Core Haptics” and “How to modify haptic events over time using CHHapticParameterCurve” for more information on that.
However, not all devices support Core Haptics, which is why you should always check for supported hardware before trying to spin up any haptic feedback. Once you added an import for CoreHaptics
, you can detect haptic availability like this:
if CHHapticEngine.capabilitiesForHardware().supportsHaptics {
// your haptics code here
}
For easier access you could also make the check a computed property, like this:
var hapticsAvailable: Bool {
CHHapticEngine.capabilitiesForHardware().supportsHaptics
}
TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 13.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.