Created
April 15, 2015 03:14
-
-
Save phatmann/e96958529cc86ff584a9 to your computer and use it in GitHub Desktop.
Encapsulate iOS background tasks in a Swift class
This file contains 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 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
If
begin
is not part of the public API (i.e. the caller who supplies the handler will never call it), it should beprivate
.