Class

NSURLSession

An object that coordinates a group of related, network data-transfer tasks.

Declaration

@interface NSURLSession : NSObject

Overview

The NSURLSession class and related classes provide an API for downloading data from and uploading data to endpoints indicated by URLs. Your app can also use this API to perform background downloads when your app isn’t running or, in iOS, while your app is suspended. You can use the related NSURLSessionDelegate and NSURLSessionTaskDelegate to support authentication and receive events like redirection and task completion.

Your app creates one or more NSURLSession instances, each of which coordinates a group of related data-transfer tasks. For example, if you’re creating a web browser, your app might create one session per tab or window, or one session for interactive use and another for background downloads. Within each session, your app adds a series of tasks, each of which represents a request for a specific URL (following HTTP redirects, if necessary).

Types of URL Sessions

The tasks within a given URL session share a common session configuration object, which defines connection behavior, like the maximum number of simultaneous connections to make to a single host, whether connections can use the cellular network, and so on.

NSURLSession has a singleton sharedSession session (which doesn’t have a configuration object) for basic requests. It’s not as customizable as sessions you create, but it serves as a good starting point if you have very limited requirements. You access this session by calling the shared class method. For other kinds of sessions, you create a NSURLSession with one of three kinds of configurations:

  • A default session behaves much like the shared session, but lets you configure it. You can also assign a delegate to the default session to obtain data incrementally.

  • Ephemeral sessions are similar to shared sessions, but don’t write caches, cookies, or credentials to disk.

  • Background sessions let you perform uploads and downloads of content in the background while your app isn't running.

See Creating a Session Configuration Object in the NSURLSessionConfiguration class for details on creating each type of configuration.

Types of URL Session Tasks

Within a session, you create tasks that optionally upload data to a server and then retrieve data from the server either as a file on disk or as one or more NSData objects in memory. The NSURLSession API provides four types of tasks:

  • Data tasks send and receive data using NSData objects. Data tasks are intended for short, often interactive requests to a server.

  • Upload tasks are similar to data tasks, but they also send data (often in the form of a file), and support background uploads while the app isn’t running.

  • Download tasks retrieve data in the form of a file, and support background downloads and uploads while the app isn’t running.

  • WebSocket tasks exchange messages over TCP and TLS, using the WebSocket protocol defined in RFC 6455.

Using a Session Delegate

Tasks in a session also share a common delegate object. You implement this delegate to provide and obtain information when various events occur, including when:

  • Authentication fails.

  • Data arrives from the server.

  • Data becomes available for caching.

If you don’t need the features provided by a delegate, you can use this API without providing one by passing nil when you create a session.

Asynchronicity and URL Sessions

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

  • By calling a completion handler block when a transfer finishes successfully or with an error.

  • By calling methods on the session’s delegate as data arrives and when the transfer is complete.

In addition to delivering this information to delegates, the NSURLSession provides status and progress properties that you can query if you need to make programmatic decisions based on the current state of the task (with the caveat that its state can change at any time).

Protocol Support

The NSURLSession class natively supports the data, file, ftp, http, and https URL schemes, with transparent support for proxy servers and SOCKS gateways, as configured in the user’s system preferences.

NSURLSession supports the HTTP/1.1 and HTTP/2 protocols. HTTP/2 support, as described by RFC 7540, requires a server that supports Application-Layer Protocol Negotiation (ALPN).

You can also add support for your own custom networking protocols and URL schemes (for your app’s private use) by subclassing NSURLProtocol.

App Transport Security (ATS)

iOS 9.0 and macOS 10.11 and later use App Transport Security (ATS) for all HTTP connections made with NSURLSession. ATS requires that HTTP connections use HTTPS (RFC 2818).

For more information, see NSAppTransportSecurity.

Foundation Copying 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 you can independently modify.

Thread Safety

The URL session API is thread-safe. You can freely create sessions and tasks in any thread context. When your delegate methods call the provided completion handlers, the work is automatically scheduled on the correct delegate queue.

Topics

Using the Shared Session

sharedSession

The shared singleton session object.

Creating a Session

+ sessionWithConfiguration:

Creates a session with the specified session configuration.

+ sessionWithConfiguration:delegate:delegateQueue:

Creates a session with the specified session configuration, delegate, and operation queue.

NSURLSessionConfiguration

A configuration object that defines behavior and policies for a URL session.

configuration

A copy of the configuration object for this session.

Working with a Delegate

delegate

The delegate assigned when this object was created.

NSURLSessionDelegate

A protocol that defines methods that URL session instances call on their delegates to handle session-level events, like session life cycle changes.

NSURLSessionTaskDelegate

A protocol that defines methods that URL session instances call on their delegates to handle task-level events.

delegateQueue

The operation queue provided when this object was created.

Adding Data Tasks to a Session

- dataTaskWithURL:

Creates a task that retrieves the contents of the specified URL.

- dataTaskWithURL:completionHandler:

Creates a task that retrieves the contents of the specified URL, then calls a handler upon completion.

- dataTaskWithRequest:

Creates a task that retrieves the contents of a URL based on the specified URL request object.

- dataTaskWithRequest:completionHandler:

Creates a task that retrieves the contents of a URL based on the specified URL request object, and calls a handler upon completion.

NSURLSessionDataTask

A URL session task that returns downloaded data directly to the app in memory.

NSURLSessionDataDelegate

A protocol that defines methods that URL session instances call on their delegates to handle task-level events specific to data and upload tasks.

Adding Download Tasks to a Session

- downloadTaskWithURL:

Creates a download task that retrieves the contents of the specified URL and saves the results to a file.

- downloadTaskWithURL:completionHandler:

Creates a download task that retrieves the contents of the specified URL, saves the results to a file, and calls a handler upon completion.

- downloadTaskWithRequest:

Creates a download task that retrieves the contents of a URL based on the specified URL request object and saves the results to a file.

- downloadTaskWithRequest:completionHandler:

Creates a download task that retrieves the contents of a URL based on the specified URL request object, saves the results to a file, and calls a handler upon completion.

- downloadTaskWithResumeData:

Creates a download task to resume a previously canceled or failed download.

- downloadTaskWithResumeData:completionHandler:

Creates a download task to resume a previously canceled or failed download and calls a handler upon completion.

NSURLSessionDownloadTask

A URL session task that stores downloaded data to file.

NSURLSessionDownloadDelegate

A protocol that defines methods that URL session instances call on their delegates to handle task-level events specific to download tasks.

Adding Upload Tasks to a Session

- uploadTaskWithRequest:fromData:

Creates a task that performs an HTTP request for the specified URL request object and uploads the provided data.

- uploadTaskWithRequest:fromData:completionHandler:

Creates a task that performs an HTTP request for the specified URL request object, uploads the provided data, and calls a handler upon completion.

- uploadTaskWithRequest:fromFile:

Creates a task that performs an HTTP request for uploading the specified file.

- uploadTaskWithRequest:fromFile:completionHandler:

Creates a task that performs an HTTP request for uploading the specified file, then calls a handler upon completion.

- uploadTaskWithStreamedRequest:

Creates a task that performs an HTTP request for uploading data based on the specified URL request.

NSURLSessionUploadTask

A URL session task that uploads data to the network in a request body.

NSURLSessionDataDelegate

A protocol that defines methods that URL session instances call on their delegates to handle task-level events specific to data and upload tasks.

Adding Stream Tasks to a Session

- streamTaskWithHostName:port:

Creates a task that establishes a bidirectional TCP/IP connection to a specified hostname and port.

- streamTaskWithNetService:

Creates a task that establishes a bidirectional TCP/IP connection using a specified network service.

NSURLSessionStreamTask

A URL session task that is stream-based.

NSURLSessionStreamDelegate

A protocol that defines methods that URL session instances call on their delegates to handle task-level events specific to stream tasks.

Adding WebSocket Tasks to a Session

- webSocketTaskWithURL:

Creates a WebSocket task for the provided URL.

- webSocketTaskWithRequest:

Creates a WebSocket task for the provided URL request.

- webSocketTaskWithURL:protocols:

Creates a WebSocket task given a URL and an array of protocols.

NSURLSessionWebSocketTask

A URL session task that communicates over the WebSockets protocol standard.

NSURLSessionWebSocketDelegate

A protocol that defines methods that URL session instances call on their delegates to handle task-level events specific to WebSocket tasks.

Managing the Session

- finishTasksAndInvalidate

Invalidates the session, allowing any outstanding tasks to finish.

- flushWithCompletionHandler:

Flushes cookies and credentials to disk, clears transient caches, and ensures that future requests occur on a new TCP connection.

- getTasksWithCompletionHandler:

Asynchronously calls a completion callback with all data, upload, and download tasks in a session.

- getAllTasksWithCompletionHandler:

Asynchronously calls a completion callback with all tasks in a session

- invalidateAndCancel

Cancels all outstanding tasks and then invalidates the session.

- resetWithCompletionHandler:

Empties all cookies, caches and credential stores, removes disk files, flushes in-progress downloads to disk, and ensures that future requests occur on a new socket.

sessionDescription

An app-defined descriptive label for the session.

Handling Errors

URL Session Error Dictionary Keys

Keys used in conjunction with error objects returned by URL sessions and tasks.

Background Task Cancellation

Constants that indicate why a background task was canceled.

Initializers

- initDeprecated

Type Methods

+ newDeprecated

Relationships

Inherits From

See Also

Essentials

Fetching Website Data into Memory

Receive data directly into memory by creating a data task from a URL session.

NSURLSessionTask

A task, like downloading a specific resource, performed in a URL session.