NSURLSession Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/Foundation.framework
Availability
Available in iOS 7.0 and later.
Companion guide
Declared in
NSURLError.h
NSURLSession.h

Overview

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:

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):

In addition, the NSURLSession API provides four protocols that define delegate methods your app can implement to provide more fine-grained control over session and task behavior.

Finally, the NSURLSession API uses a number of classes that are also commonly used with other APIs such as NSURLConnection and NSURLDownload. Some of these shared classes include:

  • NSURL—An object that contains a URL.

  • NSURLRequest—Encapsulates metadata related to a URL request, including the URL, request method, and so on.

  • NSURLResponse—Encapsulates metadata related to a server’s response to a request, such as the content MIME type and length.

    • NSHTTPURLResponse—Adds additional metadata specific to HTTP requests, such as response headers.

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

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.

Tasks

Creating a Session

Configuring a Session

Adding Data Tasks to a Session

Adding Download Tasks to a Session

Adding Upload Tasks to a Session

Managing the Session

Properties

configuration

A copy of the configuration object for this session. (read-only)

@property(readonly, copy) NSURLSessionConfiguration *configuration
Discussion

Changing mutable values within the configuration object has no effect on the current session, but you can create a new session with the modified configuration object.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

delegate

The delegate assigned when this object was created. (read-only)

@property(readonly, retain) id<NSURLSessionDelegate> delegate
Discussion

This delegate object is responsible for handling authentication challenges, for making caching decisions, and for handling other session-related events.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

delegateQueue

The operation queue provided when this object was created. (read-only)

@property(readonly, retain) NSOperationQueue *delegateQueue
Discussion

All delegate method calls and completion handlers related to the session are performed on this queue.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

sessionDescription

An app-defined descriptive label for the session.

@property(copy) NSString *sessionDescription
Discussion

This property contains human-readable strings that you can display to the user as part of your app’s user interface. This value may be nil.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

Class Methods

sessionWithConfiguration:

Creates a session with the specified session configuration.

+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration
Parameters
configuration

A configuration object that specifies certain behaviors, such as caching policies, timeouts, proxies, pipelining, TLS versions to support, cookie policies, credential storage, and so on. For more information, see NSURLSessionConfiguration Class Reference.

Discussion

If this method is used, the session creates a serial NSOperationQueue object on which to perform all delegate method calls and completion handler calls.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

sessionWithConfiguration:delegate:delegateQueue:

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

+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(id<NSURLSessionDelegate>)delegate delegateQueue:(NSOperationQueue *)queue
Parameters
configuration

A configuration object that specifies certain behaviors, such as caching policies, timeouts, proxies, pipelining, TLS versions to support, cookie policies, and credential storage.

Because the session copies the configuration object, it is safe to modify the configuration object and use it to construct additional sessions.

For more information, see NSURLSessionConfiguration Class Reference.

delegate

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.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

sharedSession

Returns a shared singleton session object.

+ (NSURLSession *)sharedSession
Discussion

The shared session uses the currently set global NSURLCache, NSHTTPCookieStorage, and NSURLCredentialStorage objects and is based on the default configuration.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

Instance Methods

dataTaskWithRequest:

Creates an HTTP request based on the specified URL request object.

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
Parameters
request

An object that provides request-specific information such as the URL, cache policy, request type, and body data or body stream.

Return Value

The new session data task.

Discussion

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

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

dataTaskWithRequest:completionHandler:

Creates an HTTP request for the specified URL request object, and calls a handler upon completion.

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler
Parameters
request

An NSURLRequest object that provides the URL, cache policy, request type, body data or body stream, and so on.

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 data task.

Discussion

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

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

dataTaskWithURL:

Creates an HTTP GET request for the specified URL.

- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url
Parameters
url

The http or https URL to be retrieved.

Return Value

The new session data task.

Discussion

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

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

dataTaskWithURL:completionHandler:

Creates an HTTP GET request for the specified URL, then calls a handler upon completion.

- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler
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.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

downloadTaskWithRequest:

Creates a download task for the specified URL request and saves the results to a file.

- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
Parameters
request

An NSURLRequest object that provides the URL, cache policy, request type, body data or body stream, and so on.

Return Value

The new session download task.

Discussion

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

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

downloadTaskWithRequest:completionHandler:

Creates a download task for the specified URL request, saves the results to a file, and calls a handler upon completion.

- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler
Parameters
request

An NSURLRequest object that provides the URL, cache policy, request type, body data or body stream, and so on.

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

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

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

downloadTaskWithResumeData:

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

- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
Parameters
resumeData

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

Return Value

The new session download task.

Discussion

Your app can obtain a resumeData object in two ways:

  • 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.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

downloadTaskWithResumeData:completionHandler:

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

- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler
Parameters
resumeData

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.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

downloadTaskWithURL:

Creates a download task for the specified URL and saves the results to a file.

- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url
Parameters
url

An NSURL object that provides the URL to download.

Return Value

The new session download task.

Discussion

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

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

downloadTaskWithURL:completionHandler:

Creates a download task for the specified URL, saves the results to a file, and calls a handler upon completion.

- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler
Parameters
url

An NSURL object that provides the URL to 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

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

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

finishTasksAndInvalidate

Invalidates the object, allowing any outstanding tasks to finish.

- (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.

To cancel all outstanding tasks, call invalidateAndCancel instead.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

flushWithCompletionHandler:

Ensures that future requests occur on a new socket and that any in-transit download data is flushed to disk.

- (void)flushWithCompletionHandler:(void (^)(void))completionHandler
Parameters
completionHandler

The completion handler to call when the flush operation is complete. This handler is executed on the delegate queue.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

getTasksWithCompletionHandler:

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

- (void)getTasksWithCompletionHandler:(void (^)(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks))completionHandler
Parameters
completionHandler

The completion handler to call with the list of currently outstanding tasks. This handler is executed on the delegate queue.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

invalidateAndCancel

Cancels all outstanding tasks and then invalidates the session object.

- (void)invalidateAndCancel
Discussion

Once invalidated, references to the delegate and callback objects are broken. Session objects cannot be reused.

To allow outstanding tasks to run until completion, call finishTasksAndInvalidate instead.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

resetWithCompletionHandler:

Resets the session asynchronously.

- (void)resetWithCompletionHandler:(void (^)(void))completionHandler
Parameters
completionHandler

The completion handler to call when the reset operation is complete. This handler is executed on the delegate queue.

Discussion

This method 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.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

uploadTaskWithRequest:fromData:

Creates an HTTP request for the specified URL request object and uploads the provided data object.

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData
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.

bodyData

The body data for the request.

Return Value

The new session upload task.

Discussion

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

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

uploadTaskWithRequest:fromData:completionHandler:

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

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler
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.

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.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

uploadTaskWithRequest:fromFile:

Creates an HTTP request for uploading the specified file URL.

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL
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.

fileURL

The URL of the file to upload.

Return Value

The new session upload task.

Discussion

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

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

uploadTaskWithRequest:fromFile:completionHandler:

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

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler
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.

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.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

uploadTaskWithStreamedRequest:

Creates an HTTP request for uploading data based on the specified URL request.

- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
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.

Return Value

The new session upload task.

Discussion

After you create the task, you must start it by calling its resume method. The upload task’s delegate must have a URLSession:task:needNewBodyStream: method that provides the body data to upload.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSURLSession.h

Constants

NSURLSession-Specific NSError userInfo Dictionary Keys

Keys used in conjunction with NSError objects returned by the NSURLSession API.

NSString *const NSURLSessionDownloadTaskResumeData;
NSString * const NSURLErrorBackgroundTaskCancelledReasonKey;
Constants
NSURLSessionDownloadTaskResumeData

A key in the error dictionary that provides resume data.

When a transfer error occurs, the delegate object or completion handler gets an NSError object. If the transfer is resumable, that error object’s userInfo dictionary contains a value for this key. To resume the transfer, your app can pass that value to the downloadTaskWithResumeData: or downloadTaskWithResumeData:completionHandler: method.

Available in iOS 7.0 and later.

Declared in NSURLSession.h.

NSURLErrorBackgroundTaskCancelledReasonKey

An NSNumber value indicating why a background task was cancelled. For a list of possible values, see “NSURLSession-Specific NSError userInfo Dictionary Keys.”

Available in iOS 7.0 and later.

Declared in NSURLError.h.

Background Task Cancellation reasons

Constants that indicate why a background task was cancelled.

enum
{
   NSURLErrorCancelledReasonUserForceQuitApplication =    0,
   NSURLErrorCancelledReasonBackgroundUpdatesDisabled =   1,
};
Constants
NSURLErrorCancelledReasonUserForceQuitApplication

The operation was canceled because the user forced the app to quit.

Available in iOS 7.0 and later.

Declared in NSURLError.h.

NSURLErrorCancelledReasonBackgroundUpdatesDisabled

The operation was canceled because background updates are disabled.

Available in iOS 7.0 and later.

Declared in NSURLError.h.

Discussion

These values are used in conjunction with the NSURLErrorBackgroundTaskCancelledReasonKey key in an NSError object’s userInfo dictionary.

NSURLSessionTaskState

Constants for determining the current state of a task.

enum NSURLSessionTaskState {
   NSURLSessionTaskStateRunning = 0,
   NSURLSessionTaskStateSuspended = 1,
   NSURLSessionTaskStateCanceling = 2,
   NSURLSessionTaskStateCompleted = 3
};
typedef NSInteger NSURLSessionTaskState;
Constants
NSURLSessionTaskStateRunning

The task is currently being serviced by the session. A task in this state is subject to the request and resource timeouts specified in the session configuration object.

Available in iOS 7.0 and later.

Declared in NSURLSession.h.

NSURLSessionTaskStateSuspended

The task was suspended by the app. No further processing takes place until it is resumed. A task in this state is not subject to timeouts.

Available in iOS 7.0 and later.

Declared in NSURLSession.h.

NSURLSessionTaskStateCanceling

The task has received a cancel message. The delegate may or may not have received a URLSession:task:didCompleteWithError: message yet. A task in this state is not subject to timeouts.

Available in iOS 7.0 and later.

Declared in NSURLSession.h.

NSURLSessionTaskStateCompleted

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.

Available in iOS 7.0 and later.

Declared in NSURLSession.h.

NSURLSessionAuthChallengeDisposition

Constants passed by session or task delegates to the provided continuation block in response to an authentication challenge.

enum NSURLSessionAuthChallengeDisposition {
   NSURLSessionAuthChallengeUseCredential = 0,
   NSURLSessionAuthChallengePerformDefaultHandling = 1,
   NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2,
   NSURLSessionAuthChallengeRejectProtectionSpace = 3,
};
typedef NSInteger NSURLSessionAuthChallengeDisposition;
Constants
NSURLSessionAuthChallengeUseCredential

Use the specified credential, which may be nil.

Available in iOS 7.0 and later.

Declared in NSURLSession.h.

NSURLSessionAuthChallengePerformDefaultHandling

Use the default handling for the challenge as though this delegate method were not implemented. The provided credential parameter is ignored.

Available in iOS 7.0 and later.

Declared in NSURLSession.h.

NSURLSessionAuthChallengeCancelAuthenticationChallenge

Cancel the entire request. The provided credential parameter is ignored.

Available in iOS 7.0 and later.

Declared in NSURLSession.h.

NSURLSessionAuthChallengeRejectProtectionSpace

Reject this challenge and call the authentication delegate method again with the next authentication protection space. The provided credential parameter is ignored.

Available in iOS 7.0 and later.

Declared in NSURLSession.h.

Transfer Size Constant

A constant denoting an unknown transfer size.

const int64_t NSURLSessionTransferSizeUnknown; /* -1LL */
Constants
NSURLSessionTransferSizeUnknown

The total size of the transfer cannot be determined.

Available in iOS 7.0 and later.

Declared in NSURLSession.h.