The NSURLSession class and related classes provide an API for downloading content via HTTP. This API provides a rich set of delegate methods for supporting authentication and gives your app the ability to perform background downloads when your app is not running or, in iOS, while your app is suspended.

With the NSURLSession API, your app creates a series of sessions, each of which coordinates a group of related data transfer tasks. For example, if you are writing a web browser, your app might create one session per tab or window. Within each session, your app adds a series of tasks, each of which represents a request for a specific URL (and for any follow-on URLs if the original URL returned an HTTP redirect).

The behavior of a session is determined by the configuration object used to create it. Because there are three types of configuration objects, there are similarly three types of sessions: default sessions that behave much like NSURLConnection, ephemeral sessions that do not cache anything to disk, and download sessions that store the results in a file and continue transferring data even when your app is suspended, exits, or crashes.

Within those sessions, you can schedule three types of tasks: data tasks for retrieving data to memory, download tasks for downloading a file to disk, and upload tasks for uploading a file from disk and receiving the response as data in memory.

Like most networking APIs, the NSURLSession API is highly asynchronous. It returns data in one of two ways, depending on the methods you call:

To a completion handler block that returns data to your app when a transfer finishes successfully or with an error.

By calling methods on your custom delegate as the data is received.

By calling methods on your custom delegate when download to a file is complete.

The NSURLSession API provides status and progress properties, in addition to delivering this information to delegates. It supports canceling, restarting or resuming, and suspending tasks, and it provides the ability to resume suspended, canceled, or failed downloads where they left off.

URL Session Class Hierarchy

The NSURLSession API consists of the following classes (nested to show subclass relationships):

NSCachedURLResponse—Encapsulates an NSURLResponse object, along with the actual body data of the server’s response, for caching purposes.

Important

The NSURLSession API involves many different classes working together in a fairly complex way that may not be obvious if you read the reference documentation by itself. Before using this API, you should read URL Loading System Programming Guide to gain a conceptual understanding of how these classes interact with one another.

NSCopying Behavior

Session and task objects conform to the NSCopying protocol as follows:

When your app copies a session or task object, you get the same object back.

When your app copies a configuration object, you get a new copy that you can independently modify.

A session delegate object that handles requests for authentication and other session-related events.

This delegate object is responsible for handling authentication challenges, for making caching decisions, and for handling other session-related events. If nil, the class uses a system-provided delegate and should be used only with methods that take completion handlers.

Important

The session object keeps a strong reference to the delegate until your app explicitly invalidates the session. If you do not invalidate the session by calling the invalidateAndCancel or resetWithCompletionHandler: method, your app leaks memory.

queue

A queue for scheduling the delegate calls and completion handlers. If nil, the session creates a serial operation queue for performing all delegate method calls and completion handler calls.

Parameters

url

The http or https URL to be retrieved.

completionHandler

The completion handler to call when the load request is complete. If sent to a session created by calling sessionWithConfiguration:delegate:delegateQueue: with a non-nil value for the delegateQueue parameter, this handler is executed on that delegate queue.

Unless you have provided a custom delegate, this parameter must not be nil, because there is no other way to retrieve the response data.

Return Value

The new session data task.

Discussion

After you create the task, you must start it by calling its resume method.

Parameters

Return Value

Discussion

If your app cancels an existing transfer by calling cancelByProducingResumeData:, the session object passes a resumeData object to the completion handler that you provided in that call.

If a transfer fails, the session object provides an NSError object either to your delegate or to the task’s completion handler. In that object, the NSURLSessionDownloadTaskResumeData key in the userInfo dictionary contains a resumeData object.

After you create the task, you must start it by calling its resume method.

Parameters

A data object that provides the data necessary to resume the download.

completionHandler

The completion handler to call when the load request is complete. This handler is executed on the delegate queue.

Unless you have provided a custom delegate, this parameter must not be nil, because there is no other way to retrieve the response data.

Return Value

The new session download task.

Discussion

Your app can obtained a resumeData object in two ways:

If your app cancels the transfer explicitly by calling cancelByProducingResumeData:, the session object passes a resumeData object to the completion handler that you provided in that call.

If a transfer fails, the session object provides an NSError object either to its delegate or to the task’s completion handler. In that object, the NSURLSessionDownloadTaskResumeData key in the userInfo dictionary contains a resumeData object.

After you create the task, you must start it by calling its resume method.

Parameters

An NSURLRequest object that provides the URL, cache policy, request type, and so on. The body stream and body data in this request object are ignored.

bodyData

The body data for the request.

completionHandler

The completion handler to call when the load request is complete. This handler is executed on the delegate queue.

Unless you have provided a custom delegate, this parameter should not be nil, because there is no other way to retrieve the response data. If you do not need the response data, use key-value observing to watch for changes to the task’s status to determine when it completes.

Return Value

The new session upload task.

Discussion

Unlike uploadTaskWithRequest:fromData:, this method returns the response body after it has been received in full, and does not require you to write a custom delegate to obtain the response body.

After you create the task, you must start it by calling its resume method.

Parameters

An NSURLRequest object that provides the URL, cache policy, request type, and so on. The body stream and body data in this request object are ignored.

fileURL

The URL of the file to upload.

completionHandler

The completion handler to call when the load request is complete. This handler is executed on the delegate queue. Unless you have provided a custom delegate, this parameter must not be nil, because there is no other way to retrieve the response data.

Return Value

The new session upload task.

Discussion

Unlike uploadTaskWithRequest:fromFile:, this method returns the response body after it has been received in full, and does not require you to write a custom delegate to obtain the response body.

After you create the task, you must start it by calling its resume method.

Declaration

Parameters

request

An NSURLRequest object that provides the URL, cache policy, request type, and so on. The body stream and body data in this request object are ignored, and NSURLSession calls its delegate’s URLSession:task:needNewBodyStream: method to provide the body data.

Availability

Declaration

Swift

funcfinishTasksAndInvalidate()

Objective-C

- (void)finishTasksAndInvalidate

Discussion

This method returns immediately without waiting for tasks to finish. Once a session is invalidated, new tasks cannot be created in the session, but existing tasks continue until completion. After the last task finishes and the session makes the last delegate call, references to the delegate and callback objects are broken. Session objects cannot be reused.

The task has completed (without being canceled), and the task's delegate receives no further callbacks. If the task completed successfully, the task’s error property is nil. Otherwise, it provides an error object that tells what went wrong. A task in this state is not subject to timeouts.