Skip to content

fix(ios): prevent thread overload by reusing CHHapticEngine - #24

Open
GorkaMinus wants to merge 2 commits into
ionic-team:mainfrom
GorkaMinus:fix/reuse-ios-haptics-engine
Open

GorkaMinus wants to merge 2 commits into
ionic-team:mainfrom
GorkaMinus:fix/reuse-ios-haptics-engine

Conversation

@GorkaMinus

Copy link
Copy Markdown

Description

This PR addresses an issue where calling Haptics.vibrate() rapidly (e.g., from a fast-scrolling picker in my case) causes the app to hang or crash on iOS. The problem stems from creating a new CHHapticEngine instance on each call, which leads to excessive thread creation and eventual system overload.

Solution:

  • Reuse a single CHHapticEngine instance across multiple vibration calls
  • Shut down the engine after duration + 5s of inactivity, so the idle countdown starts after the vibration finishes
  • Handle engine lifecycle with resetHandler (restarts engine after server recovery) and stoppedHandler (clears the reference on external stops like audio interruptions or app suspension)

Change Type

  • Fix

Rationale / Problems Fixed

Continuation of ionic-team/capacitor-plugins#2340, moved here per maintainer guidance since the haptics plugin now lives in its own repository.

Related: #7

Creating a new CHHapticEngine per vibrate() call spawns threads that accumulate faster than the system can reclaim them. Under rapid-fire usage (pickers, scroll-driven haptics), this leads to thread exhaustion, UI freezes, and eventual crashes.

Tests or Reproductions

  • Rapidly call Haptics.vibrate() from a picker/scroll, confirm no freeze or crash
  • Call vibrate(duration) with a long duration (e.g. 5s), confirm vibration completes fully before engine shuts down
  • Trigger an audio session interruption (e.g. phone call) mid-session, confirm haptics recover on next use
  • Verify fallback to AudioServicesPlayAlertSound on devices without haptic support

Platforms Affected

  • iOS

Notes / Comments

This also addresses review feedback from the original PR (ionic-team/capacitor-plugins#2340):

  • Removed redundant supportsHaptics check inside initializeEngine() since it's already guarded in the caller
  • Idle timer now accounts for vibration duration (duration + 5s) instead of a flat 5s countdown
  • Added resetHandler and stoppedHandler for proper engine lifecycle management following Apple's recommended patterns

@magnuslo

Copy link
Copy Markdown

We independently hit this exact crash in production — calling Haptics.vibrate(duration) rapidly creates a new CHHapticEngine per call and the threads accumulate until the app freezes/crashes (matches #7). We landed the same fix locally as in this PR (reuse a single CHHapticEngine, restart via resetHandler, clear the reference in stoppedHandler), and it resolved the hang on a physical device.

Just adding a +1 with an independent reproduction in the hope of getting this reviewed/merged — it's a real crash and the fix here looks correct. Happy to help test on additional devices if that unblocks it.

@OS-ruimoreiramendes OS-ruimoreiramendes self-assigned this Sep 29, 2026
Comment on lines +33 to +40
private func resetIdleTimer(after duration: TimeInterval) {
idleTimer?.invalidate()
idleTimer = Timer.scheduledTimer(
withTimeInterval: duration + idleInterval, repeats: false
) { [weak self] _ in
self?.shutdownEngine()
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
private func resetIdleTimer(after duration: TimeInterval) {
idleTimer?.invalidate()
idleTimer = Timer.scheduledTimer(
withTimeInterval: duration + idleInterval, repeats: false
) { [weak self] _ in
self?.shutdownEngine()
}
}
private func resetIdleTimer(after duration: TimeInterval) {
idleTimer?.invalidate()
DispatchQueue.main.async { [weak self] in
guard let self else { return }
self.idleTimer = Timer.scheduledTimer(
withTimeInterval: duration + self.idleInterval, repeats: false
) { [weak self] _ in
self?.shutdownEngine()
}
}
}

Timer.scheduledTimer uses the current thread's run loop. Fine on main thread, but if vibrate() is called from a background queue with no run loop, the timer never fires and the engine stays alive. Safer to force main.

Comment on lines +13 to +31
private func initializeEngine() {
do {
let engine = try CHHapticEngine()
engine.resetHandler = { [weak self] in
do {
try self?.hapticEngine?.start()
} catch {
self?.hapticEngine = nil
}
}
engine.stoppedHandler = { [weak self] _ in
self?.hapticEngine = nil
}
try engine.start()
hapticEngine = engine
} catch {
hapticEngine = nil
}
}

@OS-ruimoreiramendes OS-ruimoreiramendes Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
private func initializeEngine() {
do {
let engine = try CHHapticEngine()
engine.resetHandler = { [weak self] in
do {
try self?.hapticEngine?.start()
} catch {
self?.hapticEngine = nil
}
}
engine.stoppedHandler = { [weak self] _ in
self?.hapticEngine = nil
}
try engine.start()
hapticEngine = engine
} catch {
hapticEngine = nil
}
}
private func initializeEngine() {
do {
let engine = try CHHapticEngine()
engine.resetHandler = { [weak self] in
guard self?.hapticEngine === engine else { return }
do {
try engine.start()
} catch {
self?.hapticEngine = nil
}
}
engine.stoppedHandler = { [weak self] _ in
if self?.hapticEngine === engine {
self?.hapticEngine = nil
}
}
hapticEngine = engine
try engine.start()
} catch {
hapticEngine = nil
}
}

Inside resetHandler you use self?.hapticEngine?.start(), but the handler was registered on this specific engine. If another initializeEngine() runs meanwhile, self?.hapticEngine may point to a different one. Same issue in stoppedHandler.

Also, hapticEngine = engine runs after try engine.start(), so if a reset fires during startup, self?.hapticEngine is still nil and nothing happens.

My suggestion is to use the captured engine in the handlers, add an identity check, and assign the property before starting.

@OS-ruimoreiramendes OS-ruimoreiramendes left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @GorkaMinus, tested it and reproduced the original issue on main with a burst of 200 vibrate calls.

Left two small suggestions on edge cases (handler identity + timer run loop). Other than that LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants