From f2e23ad41895ce925643bf8c0e34c4435e927199 Mon Sep 17 00:00:00 2001 From: Jakub Kiermasz Date: Mon, 12 Aug 2024 20:45:25 +0200 Subject: [PATCH] Start/stop engine when entering background/foreground (#70) --- Sources/Pow/Infrastructure/Haptics.swift | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Sources/Pow/Infrastructure/Haptics.swift b/Sources/Pow/Infrastructure/Haptics.swift index fb659ff..22acefb 100644 --- a/Sources/Pow/Infrastructure/Haptics.swift +++ b/Sources/Pow/Infrastructure/Haptics.swift @@ -5,8 +5,21 @@ import CoreHaptics internal struct Haptics { private static var engine: CHHapticEngine? = { - return try? CHHapticEngine() + let engine = try? CHHapticEngine() + addHapticEngineObservers() + return engine }() + + private static func addHapticEngineObservers() { + // Without stopping the CHHapticEngine when entering background mode, haptics are not played when the app enters the foreground. + // See https://github.com/EmergeTools/Pow/issues/69 + NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: nil) { _ in + engine?.stop() + } + NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil) { _ in + try? engine?.start() + } + } private static var supportsHaptics = CHHapticEngine.capabilitiesForHardware().supportsHaptics