URLSession Task Types vs Session Types

This thread has been locked by a moderator.

I regularly see folks confused as to which URLSession task types are supported in which session types. Here’s a handy reference:

Task Type                 Standard Background
---------                 -------- ----------
data, convenience         yes      no
data, delegate            yes      yes [1]
  
download, convenience     yes      no
download, delegate        yes      yes

upload, convenience       yes      no
upload, delegate, data    yes      no
upload, delegate, stream  yes      no
upload, delegate, file    yes      yes

stream                    yes      no

WebSocket                 yes      no

In this table:

  • A background session is one created from a configuration that was created with the background(withIdentifier:) method.

  • A standard session is one created from some other configuration, namely default or ephemeral.

  • A convenience task is one created by a Swift async method or a method that takes a completion handler.

  • A delegate task is one created otherwise; these signal their completion by calling the urlSession(_:task:didCompleteWithError:) delegate method.

  • For an upload task, the data, stream, and file modifiers indicate how you specify the HTTP request body.

Share and Enjoy

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

[1] While it’s possible to run a data task in a background session, this only works if your app avoids suspension while the request is in flight. This is useful in very rare circumstances [2] that most developers never encounter.

[2] The specific situation I’m aware of is when you don’t know whether a request’s response will be big (like a file to download) or small (like a status response). To handle this, you start a data task in the background session and, if the response indicates that it’s large, transform it to a download task in your urlSession(_:dataTask:didReceive:completionHandler:) method.

(r. 123084713)

Up vote post of eskimo
176 views