Skip to content

Instantly share code, notes, and snippets.

@KheangSenghort
Forked from phatmann/BackgroundTask.swift
Created March 21, 2018 04:50
Show Gist options
  • Save KheangSenghort/e8d3cf05c17f8ac0a066c4fda2bb11f4 to your computer and use it in GitHub Desktop.
Save KheangSenghort/e8d3cf05c17f8ac0a066c4fda2bb11f4 to your computer and use it in GitHub Desktop.
Encapsulate iOS background tasks in a Swift class
class BackgroundTask {
private let application: UIApplication
private var identifier = UIBackgroundTaskInvalid
init(application: UIApplication) {
self.application = application
}
class func run(application: UIApplication, handler: (BackgroundTask) -> ()) {
// NOTE: The handler must call end() when it is done
let backgroundTask = BackgroundTask(application: application)
backgroundTask.begin()
handler(backgroundTask)
}
func begin() {
self.identifier = application.beginBackgroundTaskWithExpirationHandler {
self.end()
}
}
func end() {
if (identifier != UIBackgroundTaskInvalid) {
application.endBackgroundTask(identifier)
}
identifier = UIBackgroundTaskInvalid
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment