Skip to content

Instantly share code, notes, and snippets.

@HofiOne
Last active March 20, 2026 10:16
Show Gist options
  • Select an option

  • Save HofiOne/eac3a6df79d84acb96c2694a3cc1cda0 to your computer and use it in GitHub Desktop.

Select an option

Save HofiOne/eac3a6df79d84acb96c2694a3cc1cda0 to your computer and use it in GitHub Desktop.
Native iOS device vibration
#if TARGET_OS_IOS
static CHHapticEngine* hapticEngine = nil;
void Native_PlayHaptic(float intensity, float duration)
{
// Core Haptics available?
if (@available(iOS 13.0,*)) {
NSError *error = nil;
if (!hapticEngine) {
hapticEngine = [[CHHapticEngine alloc] initAndReturnError:&error];
if (!error)
[hapticEngine startAndReturnError:&error];
if (error) {
NSLog(@"Error creating haptic engine: %@", error.localizedDescription);
return;
}
}
// Clamp input
intensity = fmaxf(0.0f, fminf(intensity, 1.0f));
duration = fmaxf(0.02f, duration);
// vibration "rumble" event
CHHapticEvent *event = [[CHHapticEvent alloc] initWithEventType:CHHapticEventTypeHapticContinuous
parameters:@[
[[CHHapticEventParameter alloc] initWithParameterID:CHHapticEventParameterIDHapticIntensity value:intensity],
[[CHHapticEventParameter alloc] initWithParameterID:CHHapticEventParameterIDHapticSharpness value:0.2]
]
relativeTime:0
duration:duration];
CHHapticPattern *pattern = [[CHHapticPattern alloc] initWithEvents:@[event]
parameters:@[]
error:&error];
if (error)
NSLog(@"Error creating haptic pattern: %@", error.localizedDescription);
else {
id<CHHapticPatternPlayer> player = [hapticEngine createPlayerWithPattern:pattern error:&error];
if (!error)
[player startAtTime:0 error:&error];
if (error)
NSLog(@"Error playing haptic pattern: %@", error.localizedDescription);
}
return;
}
// Fallback for older devices -> classic vibration
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment