Skip to content

Commit f2e23ad

Browse files
authored
Start/stop engine when entering background/foreground (#70)
1 parent f0d0f3e commit f2e23ad

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

Sources/Pow/Infrastructure/Haptics.swift

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,21 @@ import CoreHaptics
55

66
internal struct Haptics {
77
private static var engine: CHHapticEngine? = {
8-
return try? CHHapticEngine()
8+
let engine = try? CHHapticEngine()
9+
addHapticEngineObservers()
10+
return engine
911
}()
12+
13+
private static func addHapticEngineObservers() {
14+
// Without stopping the CHHapticEngine when entering background mode, haptics are not played when the app enters the foreground.
15+
// See https://github.com/EmergeTools/Pow/issues/69
16+
NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: nil) { _ in
17+
engine?.stop()
18+
}
19+
NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil) { _ in
20+
try? engine?.start()
21+
}
22+
}
1023

1124
private static var supportsHaptics = CHHapticEngine.capabilitiesForHardware().supportsHaptics
1225

0 commit comments

Comments
 (0)