From 15ddb03e220bf525d9c8a02ed6a01d7fca764375 Mon Sep 17 00:00:00 2001 From: Jakub Kiermasz Date: Sun, 4 Aug 2024 18:24:03 +0200 Subject: [PATCH 1/2] Start/stop engine when entering background/foreground --- Sources/Pow/Infrastructure/Haptics.swift | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Sources/Pow/Infrastructure/Haptics.swift b/Sources/Pow/Infrastructure/Haptics.swift index fb659ff..dc74313 100644 --- a/Sources/Pow/Infrastructure/Haptics.swift +++ b/Sources/Pow/Infrastructure/Haptics.swift @@ -5,7 +5,14 @@ import CoreHaptics internal struct Haptics { private static var engine: CHHapticEngine? = { - return try? CHHapticEngine() + let engine = try? CHHapticEngine() + 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() + } + return engine }() private static var supportsHaptics = CHHapticEngine.capabilitiesForHardware().supportsHaptics From 9b5a87876385a1d0f126062b3764c867e43fdaca Mon Sep 17 00:00:00 2001 From: Jakub Kiermasz Date: Sun, 11 Aug 2024 10:14:02 +0200 Subject: [PATCH 2/2] Extract to private method --- Sources/Pow/Infrastructure/Haptics.swift | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Sources/Pow/Infrastructure/Haptics.swift b/Sources/Pow/Infrastructure/Haptics.swift index dc74313..22acefb 100644 --- a/Sources/Pow/Infrastructure/Haptics.swift +++ b/Sources/Pow/Infrastructure/Haptics.swift @@ -6,14 +6,20 @@ import CoreHaptics internal struct Haptics { private static var engine: 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() } - return engine - }() + } private static var supportsHaptics = CHHapticEngine.capabilitiesForHardware().supportsHaptics