iOS Developer Library

Developer

Foundation Framework Reference NSURLSession Class Reference

Options
Deployment Target:

On This Page
Language:

NSURLSession

Inherits From


Conforms To


Import Statement


Swift

import Foundation

Objective-C

@import Foundation;

Availability


Available in iOS 7.0 and later

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

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

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

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

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

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

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

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

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

URL Session Class Hierarchy

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

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.

  • Creates a session with the specified session configuration.

    Declaration

    Swift

    init(configuration configuration: NSURLSessionConfiguration) -> NSURLSession

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    init(configuration configuration: NSURLSessionConfiguration?, delegate delegate: NSURLSessionDelegate?, delegateQueue queue: NSOperationQueue?) -> NSURLSession

    Objective-C

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

    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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

  • Returns a shared singleton session object.

    Declaration

    Swift

    class func sharedSession() -> NSURLSession

    Objective-C

    + (NSURLSession *)sharedSession

    Discussion

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    @NSCopying var configuration: NSURLSessionConfiguration { get }

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

  • delegate delegate Property

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

    Declaration

    Swift

    var delegate: NSURLSessionDelegate? { get }

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    var delegateQueue: NSOperationQueue { get }

    Objective-C

    @property(readonly, retain) NSOperationQueue *delegateQueue

    Discussion

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

  • An app-defined descriptive label for the session.

    Declaration

    Swift

    var sessionDescription: String?

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

  • Creates an HTTP GET request for the specified URL.

    Declaration

    Swift

    func dataTaskWithURL(_ url: NSURL) -> NSURLSessionDataTask

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    func dataTaskWithURL(_ url: NSURL, completionHandler completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?) -> NSURLSessionDataTask

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    func dataTaskWithRequest(_ request: NSURLRequest) -> NSURLSessionDataTask

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    func dataTaskWithRequest(_ request: NSURLRequest, completionHandler completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?) -> NSURLSessionDataTask

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    func downloadTaskWithURL(_ url: NSURL) -> NSURLSessionDownloadTask

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    func downloadTaskWithURL(_ url: NSURL, completionHandler completionHandler: ((NSURL!, NSURLResponse!, NSError!) -> Void)?) -> NSURLSessionDownloadTask

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    func downloadTaskWithRequest(_ request: NSURLRequest) -> NSURLSessionDownloadTask

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    func downloadTaskWithRequest(_ request: NSURLRequest, completionHandler completionHandler: ((NSURL!, NSURLResponse!, NSError!) -> Void)?) -> NSURLSessionDownloadTask

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

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

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    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.

    Declaration

    Swift

    func downloadTaskWithResumeData(_ resumeData: NSData, completionHandler completionHandler: ((NSURL!, NSURLResponse!, NSError!) -> Void)?) -> NSURLSessionDownloadTask

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    func uploadTaskWithRequest(_ request: NSURLRequest, fromData bodyData: NSData?) -> NSURLSessionUploadTask

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    func uploadTaskWithRequest(_ request: NSURLRequest, fromData bodyData: NSData?, completionHandler completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?) -> NSURLSessionUploadTask

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

  • Creates an HTTP request for uploading the specified file URL.

    Declaration

    Swift

    func uploadTaskWithRequest(_ request: NSURLRequest, fromFile fileURL: NSURL) -> NSURLSessionUploadTask

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    func uploadTaskWithRequest(_ request: NSURLRequest, fromFile fileURL: NSURL, completionHandler completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?) -> NSURLSessionUploadTask

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    func uploadTaskWithStreamedRequest(_ request: NSURLRequest) -> NSURLSessionUploadTask

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

  • Invalidates the object, allowing any outstanding tasks to finish.

    Declaration

    Swift

    func finishTasksAndInvalidate()

    Objective-C

    - (void)finishTasksAndInvalidate

    Discussion

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

    To cancel all outstanding tasks, call invalidateAndCancel instead.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    func flushWithCompletionHandler(_ completionHandler: () -> Void)

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    func getTasksWithCompletionHandler(_ completionHandler: ([AnyObject]!, [AnyObject]!, [AnyObject]!) -> Void)

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

  • Cancels all outstanding tasks and then invalidates the session object.

    Declaration

    Swift

    func invalidateAndCancel()

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

  • Resets the session asynchronously.

    Declaration

    Swift

    func resetWithCompletionHandler(_ completionHandler: () -> Void)

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    let NSURLSessionDownloadTaskResumeData: String let NSURLErrorBackgroundTaskCancelledReasonKey: String

    Objective-C

    NSString *const NSURLSessionDownloadTaskResumeData; NSString * const NSURLErrorBackgroundTaskCancelledReasonKey;

    Constants

    • NSURLSessionDownloadTaskResumeData

      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

    • NSURLErrorBackgroundTaskCancelledReasonKey

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

    • NSURLErrorCancelledReasonUserForceQuitApplication

      NSURLErrorCancelledReasonUserForceQuitApplication

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

      Available in iOS 7.0 and later

    • NSURLErrorCancelledReasonBackgroundUpdatesDisabled

      NSURLErrorCancelledReasonBackgroundUpdatesDisabled

      The operation was canceled because background updates are disabled.

      Available in iOS 7.0 and later

    Discussion

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

  • Constants for determining the current state of a task.

    Declaration

    Swift

    enum NSURLSessionTaskState : Int { case Running case Suspended case Canceling case Completed }

    Objective-C

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

    Constants

    • Running

      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

    • Suspended

      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

    • Canceling

      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

    • Completed

      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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

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

    Declaration

    Swift

    enum NSURLSessionAuthChallengeDisposition : Int { case UseCredential case PerformDefaultHandling case CancelAuthenticationChallenge case RejectProtectionSpace }

    Objective-C

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

    Constants

    • UseCredential

      NSURLSessionAuthChallengeUseCredential

      Use the specified credential, which may be nil.

      Available in iOS 7.0 and later

    • PerformDefaultHandling

      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

    • CancelAuthenticationChallenge

      NSURLSessionAuthChallengeCancelAuthenticationChallenge

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

      Available in iOS 7.0 and later

    • RejectProtectionSpace

      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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later

  • A constant denoting an unknown transfer size.

    Declaration

    Swift

    let NSURLSessionTransferSizeUnknown: Int64

    Objective-C

    const int64_t NSURLSessionTransferSizeUnknown ; /* -1LL */

    Constants

    • NSURLSessionTransferSizeUnknown

      NSURLSessionTransferSizeUnknown

      The total size of the transfer cannot be determined.

      Available in iOS 7.0 and later