Last active
November 28, 2021 17:44
-
-
Save yonat/26e26bbafdd3e99608c8e22c9e7a2afd to your computer and use it in GitHub Desktop.
iOS background task with all the checks and balances
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BackgroundTaskWrapper { | |
private var taskID = UIBackgroundTaskIdentifier.invalid | |
var cancelAction: (() -> Void)? | |
func begin() { | |
guard .invalid == taskID else { return } | |
taskID = UIApplication.shared.beginBackgroundTask { [weak self] in | |
self?.cancelAction?() | |
self?.end() | |
} | |
} | |
func end() { | |
guard .invalid != taskID else { return } | |
let id = taskID | |
taskID = .invalid | |
UIApplication.shared.endBackgroundTask(id) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment