Completion handler blocks are not supported in background sessions

When I try to implement the new Background Task options in the same way as they show in the WWDC video (on watchOS) likes this:

let config = URLSessionConfiguration.background(withIdentifier: "SESSION_ID")
config.sessionSendsLaunchEvents = true
 
let session = URLSession(configuration: config)

let response = await withTaskCancellationHandler {
      try? await session.data(for: request)
} onCancel: {
      let task = session.downloadTask(with: request))
      task.resume()
}

I'm receiving the following error:

Terminating app due to uncaught exception 'NSGenericException', reason: 'Completion handler blocks are not supported in background sessions. Use a delegate instead.'

Did I forget something?

Did I forget something?

Nope.

What you’re asking for here is architecturally impossible. The typical use case for a URLSession background session runs like this:

  1. Your app starts a task.

  2. The user presses the Home button, which suspends your app. The request continues running in a system process (nsurlsessiond).

  3. After a while the system might run low on memory and it terminates your app.

  4. What the task finishes, the system relaunches your app in the background to handle the result.

You can’t use a completion handler in this scenario because it relies on state from the current process and that process is gone by the time you get to step 4.

Share and Enjoy

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

So the code above isn't explicitly using completionHandlers for the URL tasks

Is the expectation that await is essentially a "completionHandler" under the hood, and the problem is asynchronously interacting with background tasks from your app entirely?

You can't use async/await for BG tasks and you must only interact with a given BG task via the delegate?

Completion handler blocks are not supported in background sessions
 
 
Q