Post

Replies

Boosts

Views

Activity

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: 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: 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?
1
0
1.2k
Feb ’21