Using NSURLSession delegate with BackgroundTasks

It seems that apps using background processing are required to implement BackgroundTasks, but I am struggling to figure out how to do that when continuing an URLSession upload task when a device enters the background.

Currently, I use BGTaskScheduler to register a new task, and schedule that task when I enter the background:
Code Block
BGTaskScheduler.shared.register(forTaskWithIdentifier: backgroundTaskIdentifier, using: nil) { task in
    self.handleUploadTask(task)
}


The actual content of the task uses a stored uploadIdentifier to recreate the session configuration and get the relevant upload tasks. Then I add a cancel call for each to when the BGTask expires, and (unnecessarily?) resume each of those ongoing upload tasks:
Code Block
func handleUploadTask(_ task: BGTask) {
     let uploader = UploadService()
     if let identifier = uploader.uploadIdentifier {
         let sessionConfig = URLSessionConfiguration.background(withIdentifier: identifier)
         let session = URLSession(configuration: sessionConfig, delegate: firebase, delegateQueue: OperationQueue.main)
         task.expirationHandler = {
             session.getTasksWithCompletionHandler { (_, uploadTasks, _) in
                 for uploadTask in uploadTasks {
                        uploadTask.cancel()
                 }
             }
         }
         session.getTasksWithCompletionHandler { (_, uploadTasks, _) in
             for uploadTask in uploadTasks {
                    uploadTask.resume()
             }
         }
     }
 }


How do I complete the BGTask when I get a callback from my URLSession delegate in my UploadService? Are there other pieces of the puzzle I am missing?

Replies

You do not, in general, need to use background tasks when working with URLSession. Rather, if you start an upload task in a background session the task will upload even if your app is suspended (or terminated) in the background. Thus, there’s no need to involve a background task. You set up the upload task and the session will resume (or relaunch) your app in the background when it finishes.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"