Skip to content

Commit

Permalink
fix: Use appropriate background task API for app extensions (#138)
Browse files Browse the repository at this point in the history
  • Loading branch information
crleona authored Mar 19, 2024
1 parent 8bea00d commit 7231bee
Showing 1 changed file with 24 additions and 6 deletions.
30 changes: 24 additions & 6 deletions Sources/Amplitude/Plugins/Vendors/AppUtil.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,31 @@ import Foundation
}

override func beginBackgroundTask() -> BackgroundTaskCompletionCallback? {
var id: UIBackgroundTaskIdentifier = .invalid
let callback = { () in
UIApplication.shared.endBackgroundTask(id)
id = .invalid
if isRunningInAppExtension {
let semaphore = DispatchSemaphore(value: 0)
ProcessInfo.processInfo.performExpiringActivity(withReason: "Amplitude") { expired in
guard !expired else {
// If we've expired, just let the system terminate the process
return
}
semaphore.wait()
}
return {
semaphore.signal()
}
} else {
var id: UIBackgroundTaskIdentifier = .invalid
let callback = { () in
UIApplication.shared.endBackgroundTask(id)
id = .invalid
}
id = UIApplication.shared.beginBackgroundTask(withName: "amplitude", expirationHandler: callback)
return callback
}
id = UIApplication.shared.beginBackgroundTask(withName: "amplitude", expirationHandler: callback)
return callback
}

private var isRunningInAppExtension: Bool {
return Bundle.main.bundlePath.hasSuffix(".appex")
}
}
#endif
Expand Down

0 comments on commit 7231bee

Please sign in to comment.