NSURLSession
The NSURLSession class and related classes provide an API for downloading content. 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.
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. You can also add support for your own custom networking protocols and URL schemes (for your app’s private use).
With the NSURLSession API, your app creates one or more 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, or one session for interactive use and another session 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).
The tasks within a given URL session share a common session configuration object, which defines connection behavior, such as the maximum number of simultaneous connections to make to a single host, whether to allow connections over a cellular network, and so on. The behavior of a session is determined in part by which method you call when creating its configuration object:
The singleton shared session (which has no configuration object) is for basic requests. It is not as customizable as sessions that you create, but it serves as a good starting point if you have very limited requirements. You access this session by calling the
sharedSessionclass method. See that method’s discussion for more information about its limitations.Default sessions behave much like the shared session (unless you customize them further), but let you obtain data incrementally using a delegate. You can create a default session configuration by calling the
defaultSessionConfigurationmethod on theNSURLSessionConfigurationclass.Ephemeral sessions are similar to default sessions, but do not write caches, cookies, or credentials to disk. You can create an ephemeral session configuration by calling the
ephemeralSessionConfigurationmethod on theNSURLSessionConfigurationclass.Background sessions let you perform uploads and downloads of content in the background while your app is not running. You can create a background session configuration by calling the
backgroundSessionConfiguration:method on theNSURLSessionConfigurationclass.
The session configuration object also contains a reference to URL cache and cookie storage objects that may be used when making requests and handling the responses, depending on the configuration and request type.
The tasks in a session also share a common delegate that lets you provide and obtain information when various events occur—when authentication fails, when data arrives from the server, when data is ready to be cached, and so on. For all background downloads and uploads, you must provide a delegate that conforms to the NSURLSessionDownloadDelegate Objective-C protocol. Otherwise, if you don’t need any of the features provided by a delegate, you can use this API without providing a delegate by passing nil when you create a session.
Within a session, you create tasks that optionally upload data to a server, 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 three types of tasks:
Data tasks send and receive data using
NSDataobjects. 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 is not running.
Download tasks retrieve data in the form of a file, and support background downloads and uploads while the app is not running.
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:
To a completion handler block that is called when a transfer finishes successfully or with an error.
By calling methods on the session’s delegate as data is received and when the transfer is complete.
In addition to delivering this information to delegates, the NSURLSession API 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).
URL sessions also support canceling, restarting or resuming, and suspending tasks, and provide 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):
NSURLSession—A session object.NSURLSessionConfiguration—A configuration object used when initializing the session.NSURLSessionTask—The base class for tasks within a session.NSURLSessionDataTask—A task for retrieving the contents of a URL as anNSDataobjectNSURLSessionUploadTask—A task for uploading a file, then retrieving the contents of a URL as anNSDataobject
NSURLSessionDownloadTask—A task for retrieving the contents of a URL as a temporary file on diskNSURLSessionStreamTask—A task for establishing a TCP/IP connection
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.
NSURLSessionDelegate—Defines delegate methods to handle session-level eventsNSURLSessionTaskDelegate—Defines delegate methods to handle task-level events common to all task typesNSURLSessionDataDelegate—Defines delegate methods to handle task-level events specific to data and upload tasksNSURLSessionDownloadDelegate—Defines delegate methods to handle task-level events specific to download tasksNSURLSessionStreamDelegate—Defines delegate methods to handle task-level events specific to stream tasks
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 anNSURLResponseobject, along with the actual body data of the server’s response, for caching purposes.
Authentication and TLS Customization
When a server requests authentication or provides credentials during TLS negotiation, the URL session calls methods on its delegate, allowing you to handle the authentication or certificate validation in a custom manner. The method it calls depends on whether you are handling a task-specific challenge or a session-wide challenge. Table 1 shows the difference between the two.
Session-wide challenges |
Task-specific challenges |
|---|---|
|
For task-specific challenges, the session calls its delegate’s URLSession:task:didReceiveChallenge:completionHandler: method.
For session-wide authentication challenges, the session calls its delegate’s URLSession:didReceiveChallenge:completionHandler: method if that method exists. Otherwise, it calls the delegate’s URLSession:task:didReceiveChallenge:completionHandler: method.
If you do not implement these methods, when a request requires client authentication, the URL session attempts to authenticate as follows:
Using the authentication information provided as part of the requested URL, if available
By looking up Internet passwords and certificates in the user’s keychain (in OS X) or the app’s keychain (in iOS)
Then, if credentials are not available, or if the server rejects the credentials, the connection continues without authenticating. For HTTP and HTTPS requests, the connection attempt fails with an appropriate HTTP status code, and may provide alternative content (such as the public version of a private site). For other URL types (such as FTP),the connection fails with a connection failure.
App Transport Security (ATS)
Starting in iOS 9.0 and OS X v10.11, a new security feature called App Transport Security (ATS) is enabled by default for all HTTP connections made with NSURLSession. ATS requires that HTTP connections use HTTPS (RFC 2818).
For more information, see NSAppTransportSecurity in the Information Property List Key Reference.
Using an URL Session
To make a request using the NSURLSession class:
Create a session configuration. For background sessions, this configuration must contain a unique identifier. Store that identifier, and use it to reassociate with the session if your app crashes or is terminated or suspended.
Create a session, specifying a configuration object and, optionally, a delegate.
Create task objects within a session that each represent a resource request. These task objects are subclasses of
NSURLSessionTask—NSURLSessionDataTask,NSURLSessionUploadTask, orNSURLSessionDownloadTask, depending on the behavior you are trying to achieve.Each task starts out in a suspended state. After your app calls
resumeon the task, it begins downloading the specified resource.
After you start a task, the session calls methods on its delegate, as follows:
If the initial handshake with the server requires a connection-level challenge (such as an SSL client certificate),
NSURLSessioncalls either theURLSession:task:didReceiveChallenge:completionHandler:orURLSession:didReceiveChallenge:completionHandler:delegate method, as previously described in Authentication and TLS Customization.For more information about writing an authentication delegate method for
NSURLSession, read URL Session Programming Guide.If the task’s data is provided from a stream, the
NSURLSessionobject calls the delegate’sURLSession:task:needNewBodyStream:delegate method to obtain anNSInputStreamobject that provides the body data for the new request.During the initial upload of body content to the server (if applicable), the delegate periodically receives
URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:callbacks that report the progress of the upload.The server sends a response.
If the response indicates that authentication is required, the session calls its delegate’s
URLSession:task:didReceiveChallenge:completionHandler:method. Go back to step 2.If the response is an HTTP redirect response, the
NSURLSessionobject calls the delegate’sURLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:method. That delegate method calls the provided completion handler with either the providedNSURLRequestobject (to follow the redirect), a newNSURLRequestobject (to redirect to a different URL), ornil(to treat the redirect’s response body as a valid response and return it as the result).If you decide to follow the redirect, go back to step 2.
If the delegate doesn’t implement this method, the redirect is followed up to the maximum number of redirects.
For a (re-)download task created by calling
downloadTaskWithResumeData:ordownloadTaskWithResumeData:completionHandler:,NSURLSessioncalls the delegate’sURLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:method with the new task object.For a data task, the
NSURLSessionobject calls the delegate’sURLSession:dataTask:didReceiveResponse:completionHandler:method. Decide whether to convert the data task into a download task, and then call the completion callback to continue receiving data or downloading data.If your app chooses to convert the data task to a download task,
NSURLSessioncalls the delegate’sURLSession:dataTask:didBecomeDownloadTask:method with the new download task as a parameter. After this call, the delegate receives no further callbacks from the data task, and begins receiving callbacks from the download task.During the transfer from the server, the delegate periodically receives a task-level callback to report the progress of the transfer.
For a data task, the session calls the delegate’s
URLSession:dataTask:didReceiveData:method with the actual pieces of data as they are received.For a download task, the session calls the delegate’s
URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:method with the number of bytes successfully written to disk. If the user tells your app to pause the download, cancel the task by calling thecancelByProducingResumeData:method.Later, if the user asks your app to resume the download, pass the returned resume data to either the
downloadTaskWithResumeData:ordownloadTaskWithResumeData:completionHandler:method to create a new download task that continues the download. (Go to step 1.)For a data task, the
NSURLSessionobject may call the delegate’sURLSession:dataTask:willCacheResponse:completionHandler:method. Your app should then decide whether to allow caching. If you do not implement this method, the default behavior is to use the caching policy specified in the session’s configuration object.If the response is multipart encoded, the session may call the delegate’s
didReceiveResponsemethod again, followed by zero or more additionaldidReceiveDatacalls. If this happens, go to step 8 (handling thedidReceiveResponsecall).If a download task completes successfully, then the
NSURLSessionobject calls the task’sURLSession:downloadTask:didFinishDownloadingToURL:method with the location of a temporary file. Your app must either read the response data from this file or move it to a permanent location before this delegate method returns.When any task completes, the
NSURLSessionobject calls the delegate’sURLSession:task:didCompleteWithError:method with either an error object ornil(if the task completed successfully).If the download task can be resumed, the
NSErrorobject’suserInfodictionary contains a value for theNSURLSessionDownloadTaskResumeDatakey. Your app should pass this value to calldownloadTaskWithResumeData:ordownloadTaskWithResumeData:completionHandler:to create a new download task that continues the existing download.If the task cannot be resumed, your app should create a new download task and restart the transaction from the beginning.
In either case, if the transfer failed for any reason other than a server error, go to step 3 (creating and resuming task objects).
If you no longer need a session, you can invalidate it by calling either
invalidateAndCancel(to cancel outstanding tasks) orfinishTasksAndInvalidate(to allow outstanding tasks to finish before invalidating the object). If you don’t invalidate the session, it automatically goes away when your app is terminated (unless it’s a background session with active tasks).After invalidating the session, when all outstanding tasks have been canceled or have finished, the session calls the delegate's
URLSession:didBecomeInvalidWithError:method. When that delegate method returns, the session disposes of its strong reference to the delegate.
If your app cancels an in-progress download, the NSURLSession object calls the delegate’s URLSession:task:didCompleteWithError: method as though an error occurred.
Background Transfer Considerations
Because restarting your app (or waiting for the user to relaunch it) is relatively expensive, some features are unavailable in background sessions. As a result:
The session must provide a delegate for event delivery. Because your app might quit and be relaunched while the transfer is in progress, completion handler blocks are not supported. (For uploads and downloads, these delegates behave the same as for in-process transfers.)
Only HTTP and HTTPS protocols are supported. Other built-in networking protocols are not supported, and neither are custom networking protocols.
Only upload and download tasks are supported (no data tasks).
Redirects are always followed.
The number of system-wide concurrent background transfers is limited.
A background task may be cancelled if it fails to meet a system-specified throughput limit. That is to say, if a long-running task is not sending or receiving enough data over a period of time, it may be cancelled to be resumed later. Therefore, it is important to make a transfer resumable, if possible.
If the background transfer is initiated while the app is in the background, the task is treated as discretionary. In other words, it behaves like a task in a session whose configuration object’s
discretionaryproperty istrue.
If these limitations are incompatible with your app’s needs, you can also download remote resources to a file in non-background sessions. If you do, then when the user puts your iOS app into the background or quits your OS X app, pause any active downloads by calling the cancelByProducingResumeData: method. Resume the downloads when the user brings your app to the foreground again. If your app is terminated before you have obtained resume data, you’ll be unable to resume the download.
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.
Thread Safety
The URL session API itself is fully thread-safe. You can freely create sessions and tasks in any thread context, and when your delegate methods call the provided completion handlers, the work is automatically scheduled on the correct delegate queue.
-
Creates a session with the specified session configuration.
Declaration
Swift
init(configurationconfiguration: NSURLSessionConfiguration)Objective-C
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configurationParameters
configurationA configuration object that specifies certain behaviors, such as caching policies, timeouts, proxies, pipelining, TLS versions to support, cookie policies, credential storage, and so on. If
nil, the session uses a newly created default configuration object.See NSURLSessionConfiguration Class Reference for more information.
Discussion
Calling this method is equivalent to calling
sessionWithConfiguration:delegate:delegateQueue:with anildelegate and queue.Availability
Available in iOS 7.0 and later.
-
Creates a session with the specified session configuration, delegate, and operation queue.
Declaration
Swift
init(configurationconfiguration: NSURLSessionConfiguration, delegatedelegate: NSURLSessionDelegate?, delegateQueuequeue: NSOperationQueue?)Objective-C
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configurationdelegate:(id<NSURLSessionDelegate>)delegatedelegateQueue:(NSOperationQueue *)queueParameters
configurationA configuration object that specifies certain behaviors, such as caching policies, timeouts, proxies, pipelining, TLS versions to support, cookie policies, and credential storage. If
nil, the session uses a newly created default configuration object.See NSURLSessionConfiguration Class Reference for more information.
delegateA 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 should be used only with methods that take completion handlers.queueAn operation queue for scheduling the delegate calls and completion handlers. The queue need not be a serial queue. 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.
-
Returns a shared singleton session object.
Declaration
Swift
class func sharedSession() -> NSURLSessionObjective-C
+ (NSURLSession *)sharedSessionDiscussion
For basic requests, the URL session class provides a shared singleton session object that gives you a reasonable default behavior. By using the shared session, you can fetch the contents of a URL to memory with just a few lines of code.
Unlike the other session types, you do not create the shared session; you merely request it by calling
[NSURLSession sharedSession]. As a result, you don’t provide a delegate or a configuration object. Therefore, with the shared session:You cannot obtain data incrementally as it arrives from the server.
You cannot significantly customize the default connection behavior.
Your ability to perform authentication is limited.
You cannot perform background downloads or uploads while your app is not running.
The shared session uses the shared
NSURLCache,NSHTTPCookieStorage, andNSURLCredentialStorageobjects, uses a shared custom networking protocol list (configured withregisterClass:andunregisterClass:), and is based on a default configuration.When working with a shared session, you should generally avoid customizing the cache, cookie storage, or credential storage (unless you are already doing so with
NSURLConnection), because there’s a very good chance that you’ll eventually outgrow the capabilities of the default session, at which point you’ll have to rewrite all of those customizations in a manner that works with your custom URL sessions.In other words, if you’re doing anything with caches, cookies, authentication, or custom networking protocols, you should probably be using a default session instead of the shared session.
Availability
Available in iOS 7.0 and later.
-
configuration configurationPropertyA copy of the configuration object for this session. (read-only)
Declaration
Swift
@NSCopying var configuration: NSURLSessionConfiguration { get }Objective-C
@property(readonly, copy) NSURLSessionConfiguration *configurationDiscussion
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.
-
The delegate assigned when this object was created. (read-only)
Declaration
Swift
var delegate: NSURLSessionDelegate? { get }Objective-C
@property(readonly, retain) id< NSURLSessionDelegate > delegateDiscussion
This delegate object is responsible for handling authentication challenges, for making caching decisions, and for handling other session-related events. The session object keeps a strong reference to this delegate until your app exits or explicitly invalidates the session. If you do not invalidate the session, your app leaks memory until it exits.
Availability
Available in iOS 7.0 and later.
-
delegateQueue delegateQueuePropertyThe operation queue provided when this object was created. (read-only)
Declaration
Swift
var delegateQueue: NSOperationQueue { get }Objective-C
@property(readonly, retain) NSOperationQueue *delegateQueueDiscussion
All delegate method calls and completion handlers related to the session are performed on this queue. The session object keeps a strong reference to this queue until your app exits or the session object is deallocated. If you do not invalidate the session, your app leaks memory until it exits.
Availability
Available in iOS 7.0 and later.
-
sessionDescription sessionDescriptionPropertyAn app-defined descriptive label for the session.
Declaration
Swift
var sessionDescription: String?Objective-C
@property(copy) NSString *sessionDescriptionDiscussion
This property contains a human-readable string that you can use for debugging purposes. This value may be
niland defaults tonil. The value is ignored by the session.Availability
Available in iOS 7.0 and later.
-
Creates a task that retrieves the contents of the specified URL.
Declaration
Swift
func dataTaskWithURL(_url: NSURL) -> NSURLSessionDataTaskObjective-C
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)urlParameters
urlThe URL to be retrieved.
Return Value
The new session data task.
Discussion
After you create the task, you must start it by calling its
resumemethod. The task calls methods on the session’s delegate to provide you with the response metadata, response data, and so on.Availability
Available in iOS 7.0 and later.
-
Creates a task that retrieves the contents of the specified URL, then calls a handler upon completion. The task bypasses calls to delegate methods for response and data delivery, and instead provides any resulting
NSData,NSURLResponse, andNSErrorobjects inside the completion handler. Delegate methods for handling authentication challenges, however, are still called.Declaration
Swift
func dataTaskWithURL(_url: NSURL, completionHandlercompletionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTaskObjective-C
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)urlcompletionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandlerParameters
urlThe URL to be retrieved.
completionHandlerThe completion handler to call when the load request is complete. This handler is executed on the delegate queue.
If you pass
nil, only the session delegate methods are called when the task completes, making this method equivalent to thedataTaskWithRequest:method.This completion handler takes the following parameters:
dataThe data returned by the server.
responseAn object that provides response metadata, such as HTTP headers and status code. If you are making an HTTP or HTTPS request, the returned object is actually an
NSHTTPURLResponseobject.errorAn error object that indicates why the request failed, or
nilif the request was successful.Return Value
The new session data task.
Discussion
After you create the task, you must start it by calling its
resumemethod.You should pass a
nilcompletion handler only when creating tasks in sessions whose delegates include aURLSession:dataTask:didReceiveData:method.If the request completes successfully, the
dataparameter of the completion handler block contains the resource data, and theerrorparameter isnil. If the request fails, thedataparameter isniland theerrorparameter contain information about the failure. If a response from the server is received, regardless of whether the request completes successfully or fails, theresponseparameter contains that information.Availability
Available in iOS 7.0 and later.
-
Creates a task that retrieves the contents of a URL based on the specified URL request object.
Declaration
Swift
func dataTaskWithRequest(_request: NSURLRequest) -> NSURLSessionDataTaskObjective-C
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)requestParameters
requestAn 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
By creating a task based on a request object, you can tune various aspects of the task’s behavior, including the cache policy and timeout interval.
After you create the task, you must start it by calling its
resumemethod.Availability
Available in iOS 7.0 and later.
-
Creates a task that retrieves the contents of a URL based on the specified URL request object, and calls a handler upon completion. The task bypasses calls to delegate methods for response and data delivery, and instead provides any resulting
NSData,NSURLResponse, andNSErrorobjects inside the completion handler. Delegate methods for handling authentication challenges, however, are still called.Declaration
Swift
func dataTaskWithRequest(_request: NSURLRequest, completionHandlercompletionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTaskObjective-C
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)requestcompletionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandlerParameters
requestAn
NSURLRequestobject that provides the URL, cache policy, request type, body data or body stream, and so on.completionHandlerThe completion handler to call when the load request is complete. This handler is executed on the delegate queue.
If you pass
nil, only the session delegate methods are called when the task completes, making this method equivalent to thedataTaskWithRequest:method.This completion handler takes the following parameters:
dataThe data returned by the server.
responseAn object that provides response metadata, such as HTTP headers and status code. If you are making an HTTP or HTTPS request, the returned object is actually an
NSHTTPURLResponseobject.errorAn error object that indicates why the request failed, or
nilif the request was successful.Return Value
The new session data task.
Discussion
By creating a task based on a request object, you can tune various aspects of the task’s behavior, including the cache policy and timeout interval.
After you create the task, you must start it by calling its
resumemethod.You should pass a
nilcompletion handler only when creating tasks in sessions whose delegates include aURLSession:dataTask:didReceiveData:method.If the request completes successfully, the
dataparameter of the completion handler block contains the resource data, and theerrorparameter isnil. If the request fails, thedataparameter isniland theerrorparameter contain information about the failure. If a response from the server is received, regardless of whether the request completes successfully or fails, theresponseparameter contains that information.Availability
Available in iOS 7.0 and later.
-
Creates a download task that retrieves the contents of the specified URL and saves the results to a file.
Declaration
Swift
func downloadTaskWithURL(_url: NSURL) -> NSURLSessionDownloadTaskObjective-C
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)urlParameters
urlAn
NSURLobject 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
resumemethod.Availability
Available in iOS 7.0 and later.
-
Creates a download task that retrieves the contents of the specified URL, saves the results to a file, and calls a handler upon completion. The task bypasses calls to delegate methods for response and data delivery, and instead provides any resulting
NSData,NSURLResponse, andNSErrorobjects inside the completion handler. Delegate methods for handling authentication challenges, however, are still called.Declaration
Swift
func downloadTaskWithURL(_url: NSURL, completionHandlercompletionHandler: (NSURL?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDownloadTaskObjective-C
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)urlcompletionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandlerParameters
urlAn
NSURLobject that provides the URL to download.completionHandlerThe completion handler to call when the load request is complete. This handler is executed on the delegate queue.
If you pass
nil, only the session delegate methods are called when the task completes, making this method equivalent to thedownloadTaskWithURL:method.This completion handler takes the following parameters:
locationThe location of a temporary file where the server’s response is stored. You must move this file or open it for reading before your completion handler returns. Otherwise, the file is deleted, and the data is lost.
responseAn object that provides response metadata, such as HTTP headers and status code. If you are making an HTTP or HTTPS request, the returned object is actually an
NSHTTPURLResponseobject.errorAn error object that indicates why the request failed, or
nilif the request was successful.Return Value
The new session download task.
Discussion
After you create the task, you must start it by calling its
resumemethod.You should pass a
nilcompletion handler only when creating tasks in sessions whose delegates include aURLSession:downloadTask:didFinishDownloadingToURL:method.If the request completes successfully, the
locationparameter of the completion handler block contains the location of the temporary file, and theerrorparameter isnil. If the request fails, thelocationparameter isniland theerrorparameter contain information about the failure. If a response from the server is received, regardless of whether the request completes successfully or fails, theresponseparameter contains that information.Availability
Available in iOS 7.0 and later.
-
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.
Declaration
Swift
func downloadTaskWithRequest(_request: NSURLRequest) -> NSURLSessionDownloadTaskObjective-C
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)requestParameters
requestAn
NSURLRequestobject that provides the URL, cache policy, request type, body data or body stream, and so on.Return Value
The new session download task.
Discussion
By creating a task based on a request object, you can tune various aspects of the task’s behavior, including the cache policy and timeout interval.
After you create the task, you must start it by calling its
resumemethod. The task calls methods on the session’s delegate to provide you with progress notifications, the location of the resulting temporary file, and so on.Availability
Available in iOS 7.0 and later.
-
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. The task bypasses calls to delegate methods for response and data delivery, and instead provides any resulting
NSURL,NSURLResponse, andNSErrorobjects inside the completion handler. Delegate methods for handling authentication challenges, however, are still called.Declaration
Swift
func downloadTaskWithRequest(_request: NSURLRequest, completionHandlercompletionHandler: (NSURL?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDownloadTaskObjective-C
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)requestcompletionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandlerParameters
requestAn
NSURLRequestobject that provides the URL, cache policy, request type, body data or body stream, and so on.completionHandlerThe completion handler to call when the load request is complete. This handler is executed on the delegate queue.
If you pass
nil, only the session delegate methods are called when the task completes, making this method equivalent to thedownloadTaskWithRequest:method.locationThe location of a temporary file where the server’s response is stored. You must move this file or open it for reading before your completion handler returns. Otherwise, the file is deleted, and the data is lost.
responseAn object that provides response metadata, such as HTTP headers and status code. If you are making an HTTP or HTTPS request, the returned object is actually an
NSHTTPURLResponseobject.errorAn error object that indicates why the request failed, or
nilif the request was successful.Return Value
The new session download task.
Discussion
By creating a task based on a request object, you can tune various aspects of the task’s behavior, including the cache policy and timeout interval.
After you create the task, you must start it by calling its
resumemethod.You should pass a
nilcompletion handler only when creating tasks in sessions whose delegates include aURLSession:downloadTask:didFinishDownloadingToURL:method.If the request completes successfully, the
locationparameter of the completion handler block contains the location of the temporary file, and theerrorparameter isnil. If the request fails, thelocationparameter isniland theerrorparameter contain information about the failure. If a response from the server is received, regardless of whether the request completes successfully or fails, theresponseparameter contains that information.Availability
Available in iOS 7.0 and later.
-
Creates a download task to resume a previously canceled or failed download.
Declaration
Swift
func downloadTaskWithResumeData(_resumeData: NSData) -> NSURLSessionDownloadTaskObjective-C
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeDataParameters
resumeDataA data object that provides the data necessary to resume a download.
Return Value
The new session download task.
Discussion
After you create the task, you must start it by calling its
resumemethod.This method is equivalent to the
downloadTaskWithResumeData:completionHandler:with anilcompletion handler. For detailed usage information, including ways to obtain a resume data object, see that method.Availability
Available in iOS 7.0 and later.
-
Creates a download task to resume a previously canceled or failed download and calls a handler upon completion. The task bypasses calls to delegate methods for response and data delivery, and instead provides any resulting
NSURL,NSURLResponse, andNSErrorobjects inside the completion handler. Delegate methods for handling authentication challenges, however, are still called.Declaration
Swift
func downloadTaskWithResumeData(_resumeData: NSData, completionHandlercompletionHandler: (NSURL?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDownloadTaskObjective-C
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeDatacompletionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandlerParameters
resumeDataA data object that provides the data necessary to resume the download.
completionHandlerThe completion handler to call when the load request is complete. This handler is executed on the delegate queue.
If you pass
nil, only the session delegate methods are called when the task completes, making this method equivalent to thedownloadTaskWithResumeData:method.locationThe location of a temporary file where the server’s response is stored. You must move this file or open it for reading before your completion handler returns. Otherwise, the file is deleted, and the data is lost.
responseAn object that provides response metadata, such as HTTP headers and status code. If you are making an HTTP or HTTPS request, the returned object is actually an
NSHTTPURLResponseobject.errorAn error object that indicates why the request failed, or
nilif the request was successful.Return Value
The new session download task.
Discussion
You should pass a
nilcompletion handler only when creating tasks in sessions whose delegates include aURLSession:downloadTask:didFinishDownloadingToURL:method.Your app can obtain a
resumeDataobject in two ways:If your app cancels an existing transfer by calling
cancelByProducingResumeData:, the session object passes aresumeDataobject to the completion handler that you provided in that call.If a transfer fails, the session object provides an
NSErrorobject either to its delegate or to the task’s completion handler. In that object, theNSURLSessionDownloadTaskResumeDatakey in theuserInfodictionary contains aresumeDataobject.
After you create the task, you must start it by calling its
resumemethod.If the request completes successfully, the
locationparameter of the completion handler block contains the location of the temporary file, and theerrorparameter isnil. If the request fails, thelocationparameter isniland theerrorparameter contain information about the failure. If a response from the server is received, regardless of whether the request completes successfully or fails, theresponseparameter contains that information.Availability
Available in iOS 7.0 and later.
-
Creates a task that performs an HTTP request for the specified URL request object and uploads the provided data.
Declaration
Swift
func uploadTaskWithRequest(_request: NSURLRequest, fromDatabodyData: NSData) -> NSURLSessionUploadTaskObjective-C
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)requestfromData:(NSData *)bodyDataParameters
requestAn
NSURLRequestobject that provides the URL, cache policy, request type, and so on. The body stream and body data in this request object are ignored.bodyDataThe body data for the request.
Return Value
The new session upload task.
Discussion
An HTTP upload request is any request that contains a request body, such as a
POSTorPUTrequest. Upload tasks require you to provide a request object so that you can provide metadata for the upload, such as HTTP request headers.After you create the task, you must start it by calling its
resumemethod. The task calls methods on the session’s delegate to provide you with the upload’s progress, response metadata, response data, and so on.Availability
Available in iOS 7.0 and later.
-
uploadTaskWithRequest(_:fromData:completionHandler:) - 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. The task bypasses calls to delegate methods for response and data delivery, and instead provides any resulting
NSData,NSURLResponse, andNSErrorobjects inside the completion handler. Delegate methods for handling authentication challenges, however, are still called.Declaration
Swift
func uploadTaskWithRequest(_request: NSURLRequest, fromDatabodyData: NSData?, completionHandlercompletionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionUploadTaskObjective-C
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)requestfromData:(NSData *)bodyDatacompletionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandlerParameters
requestAn
NSURLRequestobject that provides the URL, cache policy, request type, and so on. The body stream and body data in this request object are ignored.bodyDataThe body data for the request.
completionHandlerThe completion handler to call when the load request is complete. This handler is executed on the delegate queue.
If you pass
nil, only the session delegate methods are called when the task completes, making this method equivalent to theuploadTaskWithRequest:fromData:method.This completion handler takes the following parameters:
dataThe data returned by the server.
responseAn object that provides response metadata, such as HTTP headers and status code. If you are making an HTTP or HTTPS request, the returned object is actually an
NSHTTPURLResponseobject.errorAn error object that indicates why the request failed, or
nilif the request was successful.Return Value
The new session upload task.
Discussion
An HTTP upload request is any request that contains a request body, such as a
POSTorPUTrequest. Upload tasks require you to provide a request object so that you can provide metadata for the upload, such as HTTP request headers.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
resumemethod.You should usually pass a
nilcompletion handler only when creating tasks in sessions whose delegates include aURLSession:dataTask:didReceiveData:method. However, 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.If the request completes successfully, the
dataparameter of the completion handler block contains the resource data, and theerrorparameter isnil. If the request fails, thedataparameter isniland theerrorparameter contain information about the failure. If a response from the server is received, regardless of whether the request completes successfully or fails, theresponseparameter contains that information.Availability
Available in iOS 7.0 and later.
-
Creates a task that performs an HTTP request for uploading the specified file.
Declaration
Swift
func uploadTaskWithRequest(_request: NSURLRequest, fromFilefileURL: NSURL) -> NSURLSessionUploadTaskObjective-C
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)requestfromFile:(NSURL *)fileURLParameters
requestAn
NSURLRequestobject that provides the URL, cache policy, request type, and so on. The body stream and body data in this request object are ignored.fileURLThe URL of the file to upload.
Return Value
The new session upload task.
Discussion
An HTTP upload request is any request that contains a request body, such as a
POSTorPUTrequest. Upload tasks require you to provide a request object so that you can provide metadata for the upload, such as HTTP request headers.After you create the task, you must start it by calling its
resumemethod. The task calls methods on the session’s delegate to provide you with the upload’s progress, response metadata, response data, and so on.Availability
Available in iOS 7.0 and later.
-
uploadTaskWithRequest(_:fromFile:completionHandler:) - uploadTaskWithRequest:fromFile:completionHandler:Creates a task that performs an HTTP request for uploading the specified file, then calls a handler upon completion. The task bypasses calls to delegate methods for response and data delivery, and instead provides any resulting
NSData,NSURLResponse, andNSErrorobjects inside the completion handler. Delegate methods for handling authentication challenges, however, are still called.Declaration
Swift
func uploadTaskWithRequest(_request: NSURLRequest, fromFilefileURL: NSURL, completionHandlercompletionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionUploadTaskObjective-C
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)requestfromFile:(NSURL *)fileURLcompletionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandlerParameters
requestAn
NSURLRequestobject that provides the URL, cache policy, request type, and so on. The body stream and body data in this request object are ignored.fileURLThe URL of the file to upload.
completionHandlerThe completion handler to call when the load request is complete. This handler is executed on the delegate queue.
If you pass
nil, only the session delegate methods are called when the task completes, making this method equivalent to theuploadTaskWithRequest:fromFile:method.This completion handler takes the following parameters:
dataThe data returned by the server.
responseAn object that provides response metadata, such as HTTP headers and status code. If you are making an HTTP or HTTPS request, the returned object is actually an
NSHTTPURLResponseobject.errorAn error object that indicates why the request failed, or
nilif the request was successful.Return Value
The new session upload task.
Discussion
An HTTP upload request is any request that contains a request body, such as a
POSTorPUTrequest. Upload tasks require you to provide a request object so that you can provide metadata for the upload, such as HTTP request headers.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
resumemethod.You should usually pass a
nilcompletion handler only when creating tasks in sessions whose delegates include aURLSession:dataTask:didReceiveData:method. However, 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.If the request completes successfully, the
dataparameter of the completion handler block contains the resource data, and theerrorparameter isnil. If the request fails, thedataparameter isniland theerrorparameter contain information about the failure. If a response from the server is received, regardless of whether the request completes successfully or fails, theresponseparameter contains that information.Availability
Available in iOS 7.0 and later.
-
Creates a task that performs an HTTP request for uploading data based on the specified URL request.
Declaration
Swift
func uploadTaskWithStreamedRequest(_request: NSURLRequest) -> NSURLSessionUploadTaskObjective-C
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)requestParameters
requestAn
NSURLRequestobject that provides the URL, cache policy, request type, and so on. The body stream and body data in this request object are ignored, andNSURLSessioncalls its delegate’sURLSession:task:needNewBodyStream:method to provide the body data.Return Value
The new session upload task.
Discussion
An HTTP upload request is any request that contains a request body, such as a
POSTorPUTrequest. Upload tasks require you to provide a request object so that you can provide metadata for the upload, such as HTTP request headers.After you create the task, you must start it by calling its
resumemethod. The task calls methods on the session’s delegate to provide you with the upload’s progress, response metadata, response data, and so on. The session’s delegate must have aURLSession:task:needNewBodyStream:method that provides the body data to upload.Availability
Available in iOS 7.0 and later.
-
Creates a task that establishes a bidirectional TCP/IP connection to a specified hostname and port.
Declaration
Swift
func streamTaskWithHostName(_hostname: String, portport: Int) -> NSURLSessionStreamTaskObjective-C
- (NSURLSessionStreamTask *)streamTaskWithHostName:(NSString *)hostnameport:(NSInteger)portParameters
hostnameThe hostname of the connection endpoint.
portThe port of the connection endpoint.
Return Value
The new session stream task.
Discussion
After you create the task, you must start it by calling its
resumemethod.Availability
Available in iOS 9.0 and later.
-
Creates a task that establishes a bidirectional TCP/IP connection using a specified network service.
Declaration
Swift
func streamTaskWithNetService(_service: NSNetService) -> NSURLSessionStreamTaskObjective-C
- (NSURLSessionStreamTask *)streamTaskWithNetService:(NSNetService *)serviceParameters
serviceAn
NSNetServiceobject used to determine the endpoint of the TCP/IP connection. This network service is resolved before any data is read or written to the resulting stream task.Return Value
The new session stream task.
Discussion
After you create the task, you must start it by calling its
resumemethod.Availability
Available in iOS 9.0 and later.
-
Invalidates the session, allowing any outstanding tasks to finish.
Declaration
Swift
func finishTasksAndInvalidate()Objective-C
- (void)finishTasksAndInvalidateDiscussion
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 related to those tasks, the session calls the
URLSession:didBecomeInvalidWithError:method on its delegate, then breaks references to the delegate and callback objects. After invalidation, session objects cannot be reused.To cancel all outstanding tasks, call
invalidateAndCancelinstead.Availability
Available in iOS 7.0 and later.
-
Flushes cookies and credentials to disk, clears transient caches, and ensures that future requests occur on a new TCP connection.
Declaration
Swift
func flushWithCompletionHandler(_completionHandler: () -> Void)Objective-C
- (void)flushWithCompletionHandler:(void (^)(void))completionHandlerParameters
completionHandlerThe 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.
-
Asynchronously calls a completion callback with all data, upload, and download tasks in a session.
Declaration
Swift
func getTasksWithCompletionHandler(_completionHandler: ([NSURLSessionDataTask], [NSURLSessionUploadTask], [NSURLSessionDownloadTask]) -> Void)Objective-C
- (void)getTasksWithCompletionHandler:(void (^)(NSArray<NSURLSessionDataTask *> *dataTasks, NSArray<NSURLSessionUploadTask *> *uploadTasks, NSArray<NSURLSessionDownloadTask *> *downloadTasks))completionHandlerParameters
completionHandlerThe completion handler to call with the list of tasks. This handler is executed on the delegate queue.
Discussion
The returned arrays contain any tasks that you have created within the session, not including any tasks that have been invalidated after completing, failing, or being cancelled.
Availability
Available in iOS 7.0 and later.
-
Cancels all outstanding tasks and then invalidates the session.
Declaration
Swift
func invalidateAndCancel()Objective-C
- (void)invalidateAndCancelDiscussion
Once invalidated, references to the delegate and callback objects are broken. After invalidation, session objects cannot be reused.
To allow outstanding tasks to run until completion, call
finishTasksAndInvalidateinstead.Availability
Available in iOS 7.0 and later.
-
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.
Declaration
Swift
func resetWithCompletionHandler(_completionHandler: () -> Void)Objective-C
- (void)resetWithCompletionHandler:(void (^)(void))completionHandlerParameters
completionHandlerThe completion handler to call when the reset operation is complete. This handler is executed on the delegate queue.
Availability
Available in iOS 7.0 and later.
-
Keys used in conjunction with
NSErrorobjects returned by theNSURLSessionAPI.Declaration
Swift
let NSURLSessionDownloadTaskResumeData: String let NSURLErrorBackgroundTaskCancelledReasonKey: StringObjective-C
NSString * const NSURLSessionDownloadTaskResumeData; NSString * const NSURLErrorBackgroundTaskCancelledReasonKey;Constants
-
NSURLSessionDownloadTaskResumeDataNSURLSessionDownloadTaskResumeDataA key in the error dictionary that provides resume data.
When a transfer error occurs or when you call the
cancelByProducingResumeData:method, the delegate object or completion handler gets anNSErrorobject. If the transfer is resumable, that error object’suserInfodictionary contains a value for this key. To resume the transfer, your app can pass that value to thedownloadTaskWithResumeData:ordownloadTaskWithResumeData:completionHandler:method.Available in iOS 7.0 and later.
-
NSURLErrorBackgroundTaskCancelledReasonKeyNSURLErrorBackgroundTaskCancelledReasonKeyAn
NSNumbervalue indicating why a background task was cancelled. For a list of possible values, see NSURLSession-Specific NSError userInfo Dictionary Keys.Available in iOS 8.0 and later.
-
-
Constants that indicate why a background task was cancelled.
Declaration
Swift
var NSURLErrorCancelledReasonUserForceQuitApplication: Int { get } var NSURLErrorCancelledReasonBackgroundUpdatesDisabled: Int { get }Objective-C
enum { NSURLErrorCancelledReasonUserForceQuitApplication = 0, NSURLErrorCancelledReasonBackgroundUpdatesDisabled = 1, };Constants
-
NSURLErrorCancelledReasonUserForceQuitApplicationNSURLErrorCancelledReasonUserForceQuitApplicationThe operation was canceled because the user forced the app to quit.
Available in iOS 7.0 and later.
-
NSURLErrorCancelledReasonBackgroundUpdatesDisabledNSURLErrorCancelledReasonBackgroundUpdatesDisabledThe operation was canceled because background updates are disabled. See Background Execution for more information.
Available in iOS 7.0 and later.
Discussion
These values are used in conjunction with the
NSURLErrorBackgroundTaskCancelledReasonKeykey in anNSErrorobject’suserInfodictionary. -
-
A constant denoting an unknown transfer size.
Declaration
Swift
let NSURLSessionTransferSizeUnknown: Int64Objective-C
const int64_t NSURLSessionTransferSizeUnknown ; /* -1LL */Constants
Copyright © 2016 Apple Inc. All rights reserved. Terms of Use | Privacy Policy | Updated: 2013-12-16
