diff --git a/Sources/TelemetryDeck/Signals/SignalManager.swift b/Sources/TelemetryDeck/Signals/SignalManager.swift index a5a969f..5ab10c0 100644 --- a/Sources/TelemetryDeck/Signals/SignalManager.swift +++ b/Sources/TelemetryDeck/Signals/SignalManager.swift @@ -147,9 +147,23 @@ final class SignalManager: SignalManageable, @unchecked Sendable { // MARK: - Notifications private extension SignalManager { + @MainActor @objc func appWillTerminate() { configuration.logHandler?.log(.debug, message: #function) - signalCache.backupCache() + + #if os(watchOS) || os(macOS) + self.signalCache.backupCache() + #else + // run backup in background task to avoid blocking main thread while ensuring app stays open during write + let backgroundTaskID = UIApplication.shared.beginBackgroundTask() + DispatchQueue.global(qos: .background).async { + self.signalCache.backupCache() + + DispatchQueue.main.async { + UIApplication.shared.endBackgroundTask(backgroundTaskID) + } + } + #endif } /// WatchOS doesn't have a notification before it's killed, so we have to use background/foreground @@ -168,13 +182,26 @@ private extension SignalManager { sendCachedSignalsRepeatedly() } + @MainActor @objc func didEnterBackground() { configuration.logHandler?.log(.debug, message: #function) sendTimer?.invalidate() sendTimer = nil - signalCache.backupCache() + #if os(watchOS) || os(macOS) + self.signalCache.backupCache() + #else + // run backup in background task to avoid blocking main thread while ensuring app stays open during write + let backgroundTaskID = UIApplication.shared.beginBackgroundTask() + DispatchQueue.global(qos: .background).async { + self.signalCache.backupCache() + + DispatchQueue.main.async { + UIApplication.shared.endBackgroundTask(backgroundTaskID) + } + } + #endif } #endif }