Skip to content

Commit

Permalink
Merge pull request #187 from TelemetryDeck/feature/file-io-main
Browse files Browse the repository at this point in the history
Avoid blocking main thread for backupCache calls when leaving app
  • Loading branch information
Jeehut authored Oct 2, 2024
2 parents 296d34b + 275901d commit 005d1f4
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions Sources/TelemetryDeck/Signals/SignalManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
Expand Down

0 comments on commit 005d1f4

Please sign in to comment.