Skip to content

Instantly share code, notes, and snippets.

@phatmann
Created April 15, 2015 03:14
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save phatmann/e96958529cc86ff584a9 to your computer and use it in GitHub Desktop.
Save phatmann/e96958529cc86ff584a9 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
}
}
@matoelorriaga
Copy link

func startBackgroundTask() {
    let application = UIApplication.sharedApplication()
    BackgroundTask.run(application) { backgroundTask in
        print("end")
        backgroundTask.end()
    }
    print("begin")
}

prints out in the console:

end
begin

what is the proper behavior/usage of this class?
maybe i don't understanding well..

thanks

@markgaensicke
Copy link

This is correct. Please don't confuse it with an async block of code that you would run on a Dispatch background queue. BackgroundTask's job is just to tell UIKit that the code (task) was ran, i.e. the background task finished. Usually you would use this in the application delegate function:

func applicationWillResignActive(application: UIApplication) {
    BackgroundTask.run(application) { backgroundTask in
        print("I'll do something that takes a few seconds")
        // calculate pi to the last digit...
        print("OK, done with the stuff")
        backgroundTask.end()
    }
}

@KheangSenghort
Copy link

When I try to apply over code in my project but it not work? Can you help me? What should do when I try reconnect socket during Foreground app long time?

@mattneub
Copy link

If begin is not part of the public API (i.e. the caller who supplies the handler will never call it), it should be private.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment