Receive data directly into memory by creating a data task from a URL session.
For small interactions with remote servers, you can use the
URLSession class to receive response data into memory (as opposed to using the
URLSession class, which stores the data directly to the file system). A data task is ideal for uses like calling a web service endpoint.
You use a URL session instance to create the task. If your needs are fairly simple, you can use the
shared instance of the
URLSession class. If you want to interact with the transfer through delegate callbacks, you’ll need to create a session instead of using the shared instance. You use a
URLSession instance when creating a session, also passing in a class that implements
URLSession or one of its subprotocols. Sessions can be reused to create multiple tasks, so for each unique configuration you need, create a session and store it as a property.
Once you have a session, you create a data task with one of the
data methods. Tasks are created in a suspended state, and can be started by calling
Receive Results with a Completion Handler
The simplest way to fetch data is to create a data task that uses a completion handler. With this arrangement, the task delivers the server’s response, data, and possibly errors to a completion handler block that you provide. Figure 1 shows the relationship between a session and a task, and how results are delivered to the completion handler.
To create a data task that uses a completion handler, call the
data method of
URLSession. Your completion handler needs to do three things:
Verify that the
nil. If not, a transport error has occurred; handle the error and exit.
responseparameter to verify that the status code indicates success and that the MIME type is an expected value. If not, handle the server error and exit.
datainstance as needed.
Listing 1 shows a
start method for fetching a URL’s contents. It starts by using the
URLSession class’s shared instance to create a data task that delivers its results to a completion handler. After checking for local and server errors, this handler converts the data to a string, and uses it to populate a
WKWeb outlet. Of course, your app might have other uses for fetched data, like parsing it into a data model.
Receive Transfer Details and Results with a Delegate
For a greater level of access to the task’s activity as it proceeds, when creating the data task, you can set a delegate on the session, rather than providing a completion handler. Figure 2 shows this arrangement.
With this approach, portions of the data are provided to the
url method of
URLSession as they arrive, until the transfer finishes or fails with an error. The delegate also receives other kinds of events as the transfer proceeds.
You need to create your own
URLSession instance when using the delegate approach, rather than using the
URLSession class’s simple
shared instance. Creating a new session allows you to set your own class as the session’s delegate, as shown in Listing 2.
Declare that your class implements one or more of the delegate protocols (
URLSession). Then create the URL session instance with the initializer
init(configuration:. You can customize the configuration instance used with this initializer. For example, it’s a good idea to set
true. That way, the session waits for suitable connectivity, rather than failing immediately if the required connectivity is unavailable.
Listing 3 shows a
start method that uses this session to start a data task, and uses delegate callbacks to handle received data and errors. This listing implements three delegate callbacks:
urlverifies that the response has a succesful HTTP status code, and that the MIME type is
Session(_: data Task: did Receive: completion Handler:)
text/plain. If either of these is not the case, the task is canceled; otherwise, it’s allowed to proceed.
Session(_: data Task: did Receive:)
Datainstance received by the task and appends it to a buffer called
urlfirst looks to see if a transport-level error has occurred. If there is no error, it attempts to convert the
Session(_: task: did Complete With Error:)
receivedbuffer to a string and set it as the contents of
The various delegate protocols offer methods beyond those shown in the above code, for handling authentication challenges, following redirects, and other special cases. Using a URL Session, in the
URLSession discussion, describes the various callbacks that may occur during a transfer.