Skip to content

Instantly share code, notes, and snippets.

@yonat
Last active November 28, 2021 17:44
Show Gist options
  • Save yonat/26e26bbafdd3e99608c8e22c9e7a2afd to your computer and use it in GitHub Desktop.
Save yonat/26e26bbafdd3e99608c8e22c9e7a2afd to your computer and use it in GitHub Desktop.
iOS background task with all the checks and balances
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