Class

URLSessionDownloadTask

A URL session task that stores downloaded data to file.

Overview

An URLSessionDownloadTask is a concrete subclass of URLSessionTask. Most of the methods associated with this class are documented in URLSessionTask.

Download tasks directly write the server’s response data to a temporary file, providing your app with progress updates as data arrives from the server. When you use download tasks in background sessions, these downloads continue even when your app is suspended or is otherwise not running.

You can pause (cancel) download tasks and resume them later (assuming the server supports doing so). You can also resume downloads that failed because of network connectivity problems.

Download Delegate Behavior

When you use a download task, your delegate receives several callbacks unique to download scenarios.

Table 1

NSError Codes for Server-Side Download Errors

HTTPS Status

NSError code

401 Unauthorized

NSURLErrorUserAuthenticationRequired

403 Unauthorized

NSURLErrorNoPermissionsToReadFile

407 Proxy Authentication Required

NSURLErrorUserAuthenticationRequired

(other)

NSURLErrorFileDoesNotExist

Topics

Canceling a Download

func cancel(byProducingResumeData: (Data?) -> Void)

Cancels a download and calls a callback with resume data for later use.

Relationships

Inherits From

Conforms To

See Also

Adding Download Tasks to a Session

func downloadTask(with: URL) -> URLSessionDownloadTask

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

func downloadTask(with: URL, completionHandler: (URL?, URLResponse?, Error?) -> Void) -> URLSessionDownloadTask

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

func downloadTask(with: URLRequest) -> URLSessionDownloadTask

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.

func downloadTask(with: URLRequest, completionHandler: (URL?, URLResponse?, Error?) -> Void) -> URLSessionDownloadTask

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.

func downloadTask(withResumeData: Data) -> URLSessionDownloadTask

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

func downloadTask(withResumeData: Data, completionHandler: (URL?, URLResponse?, Error?) -> Void) -> URLSessionDownloadTask

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

protocol URLSessionDownloadDelegate

A protocol defining methods that URLSession instances call on their delegates to handle task-level events specific to download tasks.