<!--
{
  "availability" : [
    "iOS: 7.0.0 -",
    "iPadOS: 7.0.0 -",
    "macCatalyst: 13.1.0 -",
    "macOS: 10.9.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/URLSession",
  "metadataVersion" : "0.1.0",
  "role" : "Class",
  "symbol" : {
    "kind" : "Class",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSURLSession"
  },
  "title" : "URLSession"
}
-->

# URLSession

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

```
class URLSession
```

## Overview

The [`URLSession`](/documentation/Foundation/URLSession) class and related classes provide an API for downloading data from and uploading data to endpoints indicated by URLs. Your app can also use this API to perform background downloads when your app isn’t running or, in iOS, while your app is suspended. You can use the related [`URLSessionDelegate`](/documentation/Foundation/URLSessionDelegate) and [`URLSessionTaskDelegate`](/documentation/Foundation/URLSessionTaskDelegate) to support authentication and receive events like redirection and task completion.

> Note:
> The ``doc://com.apple.foundation/documentation/Foundation/URLSession`` API involves many different classes that work together in a fairly complex way which may not be obvious if you read the reference documentation by itself. Before using the API, read the overview in the <doc://com.apple.foundation/documentation/Foundation/url-loading-system> topic. The articles in the Essentials, Uploading, and Downloading sections offer examples of performing common tasks with ``doc://com.apple.foundation/documentation/Foundation/URLSession``.

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

### Types of URL sessions

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

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

- A default session behaves much like the shared session, but lets you configure it. You can also assign a delegate to the default session to obtain data incrementally.
- Ephemeral sessions are similar to shared sessions, but don’t write caches, cookies, or credentials to disk.
- Background sessions let you perform uploads and downloads of content in the background while your app isn’t running.

See Creating a session configuration object in the [`URLSessionConfiguration`](/documentation/Foundation/URLSessionConfiguration) class for details on creating each type of configuration.

### Types of URL session tasks

Within a session, you create tasks that optionally upload data to a server and then retrieve data from the server either as a file on disk or as one or more [`NSData`](/documentation/Foundation/NSData) objects in memory. The [`URLSession`](/documentation/Foundation/URLSession) API provides four types of tasks:

- Data tasks send and receive data using ``doc://com.apple.foundation/documentation/Foundation/NSData`` objects. Data tasks are intended for short, often interactive requests to a server.
- Upload tasks are similar to data tasks, but they also send data (often in the form of a file), and support background uploads while the app isn’t running.
- Download tasks retrieve data in the form of a file, and support background downloads and uploads while the app isn’t running.
- WebSocket tasks exchange messages over TCP and TLS, using the WebSocket protocol defined in [RFC 6455](https://tools.ietf.org/html/rfc6455).

### Using a session delegate

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

- Authentication fails.
- Data arrives from the server.
- Data becomes available for caching.

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

> Important:
> The session object keeps a strong reference to the delegate until your app exits or explicitly invalidates the session. If you don’t invalidate the session, your app leaks memory until the app terminates.

Each task you create with the session calls back to the session’s delegate, using the methods defined in [`URLSessionTaskDelegate`](/documentation/Foundation/URLSessionTaskDelegate). You can also intercept these callbacks before they reach the session delegate by populating a separate [`delegate`](/documentation/Foundation/URLSessionTask/delegate) that’s specific to the task.

### Asynchronicity and URL sessions

Like most networking APIs, the [`URLSession`](/documentation/Foundation/URLSession) API is highly asynchronous. It returns data to your app in one of three ways, depending on the methods you call:

- If you’re using Swift, you can use the methods marked with the `async` keyword to perform common tasks. For example, ``doc://com.apple.foundation/documentation/Foundation/URLSession/data(from:delegate:)`` fetches data, while ``doc://com.apple.foundation/documentation/Foundation/URLSession/download(from:delegate:)`` downloads files. Your call point uses the `await` keyword to suspend running until the transfer completes. You can also use the ``doc://com.apple.foundation/documentation/Foundation/URLSession/bytes(from:delegate:)`` method to receive data as an <doc://com.apple.documentation/documentation/Swift/AsyncSequence>. With this approach, you use the `for`-`await`-`in` syntax to iterate over the data as your app receives it. The ``doc://com.apple.foundation/documentation/Foundation/URL`` type also offers covenience methods to fetch bytes or lines from the shared URL session.
- In Swift or Objective-C, you can provide a completion handler block, which runs when the transfer completes.
- In Swift or Objective-C, you can receive callbacks to a delegate method as the transfer progresses and immediately after it completes.

In addition to delivering this information to delegates, the [`URLSession`](/documentation/Foundation/URLSession) provides status and progress properties. Query these properties if you need to make programmatic decisions based on the current state of the task (with the caveat that its state can change at any time).

### Protocol support

The [`URLSession`](/documentation/Foundation/URLSession) 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.

[`URLSession`](/documentation/Foundation/URLSession) supports the HTTP/1.1, HTTP/2, and HTTP/3 protocols. HTTP/2 support, as described by [RFC 7540](https://tools.ietf.org/html/rfc7540), requires a server that supports Application-Layer Protocol Negotiation (ALPN).

You can also add support for your own custom networking protocols and URL schemes (for your app’s private use) by subclassing [`URLProtocol`](/documentation/Foundation/URLProtocol).

### App Transport Security (ATS)

iOS 9.0 and macOS 10.11 and later use App Transport Security (ATS) for all HTTP connections made with [`URLSession`](/documentation/Foundation/URLSession). ATS requires that HTTP connections use HTTPS ([RFC 2818](https://tools.ietf.org/html/rfc2818)).

For more information, see <doc://com.apple.documentation/documentation/BundleResources/Information-Property-List/NSAppTransportSecurity>.

### Foundation copying behavior

Session and task objects conform to the [`NSCopying`](/documentation/Foundation/NSCopying) protocol as follows:

- When your app copies a session or task object, you get the same object back.
- When your app copies a configuration object, you get a new copy you can independently modify.

### Thread safety

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

## Topics

### Using the shared session

[`shared`](/documentation/Foundation/URLSession/shared)

The shared singleton session object.

### Creating a session

[`init(configuration:)`](/documentation/Foundation/URLSession/init(configuration:))

Creates a session with the specified session configuration.

[`init(configuration:delegate:delegateQueue:)`](/documentation/Foundation/URLSession/init(configuration:delegate:delegateQueue:))

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

[`URLSessionConfiguration`](/documentation/Foundation/URLSessionConfiguration)

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

[`configuration`](/documentation/Foundation/URLSession/configuration)

A copy of the configuration object for this session.

### Working with a delegate

[`delegate`](/documentation/Foundation/URLSession/delegate)

The delegate assigned when this object was created.

[`URLSessionDelegate`](/documentation/Foundation/URLSessionDelegate)

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

[`URLSessionTaskDelegate`](/documentation/Foundation/URLSessionTaskDelegate)

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

[`delegateQueue`](/documentation/Foundation/URLSession/delegateQueue)

The operation queue provided when this object was created.

### Performing asynchronous transfers

[`bytes(for:delegate:)`](/documentation/Foundation/URLSession/bytes(for:delegate:))

Retrieves the contents of a URL based on the specified URL request and delivers an asynchronous sequence of bytes.

[`bytes(from:delegate:)`](/documentation/Foundation/URLSession/bytes(from:delegate:))

Retrieves the contents of a given URL and delivers an asynchronous sequence of bytes.

[`URLSession.AsyncBytes`](/documentation/Foundation/URLSession/AsyncBytes)

An asynchronous sequence of bytes.

[`data(for:delegate:)`](/documentation/Foundation/URLSession/data(for:delegate:))

Downloads the contents of a URL based on the specified URL request and delivers the data asynchronously.

[`data(from:delegate:)`](/documentation/Foundation/URLSession/data(from:delegate:))

Retrieves the contents of a URL and delivers the data asynchronously.

[`data(for:)`](/documentation/Foundation/URLSession/data(for:))

Convenience method to load data using a URLRequest, creates and resumes a URLSessionDataTask internally.

[`data(from:)`](/documentation/Foundation/URLSession/data(from:))

Convenience method to load data using a URL, creates and resumes a URLSessionDataTask internally.

[`download(for:delegate:)`](/documentation/Foundation/URLSession/download(for:delegate:))

Retrieves the contents of a URL based on the specified URL request and delivers the URL of the saved file asynchronously.

[`download(from:delegate:)`](/documentation/Foundation/URLSession/download(from:delegate:))

Retrieves the contents of a URL and delivers the URL of the saved file asynchronously.

[`download(resumeFrom:delegate:)`](/documentation/Foundation/URLSession/download(resumeFrom:delegate:))

Resumes a previously-paused download and delivers the URL of the saved file asynchronously.

[`upload(for:from:delegate:)`](/documentation/Foundation/URLSession/upload(for:from:delegate:))

Uploads data to a URL based on the specified URL request and delivers the result asynchronously.

[`upload(for:fromFile:delegate:)`](/documentation/Foundation/URLSession/upload(for:fromFile:delegate:))

Uploads data to a URL and delivers the result asynchronously.

[`upload(for:from:)`](/documentation/Foundation/URLSession/upload(for:from:))

Convenience method to upload data using a URLRequest, creates and resumes a URLSessionUploadTask internally.

[`upload(for:fromFile:)`](/documentation/Foundation/URLSession/upload(for:fromFile:))

Convenience method to upload data using a URLRequest, creates and resumes a URLSessionUploadTask internally.

[`URLSessionTaskDelegate`](/documentation/Foundation/URLSessionTaskDelegate)

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

### Adding data tasks to a session

[`dataTask(with:)`](/documentation/Foundation/URLSession/dataTask(with:)-10dy7)

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

[`dataTask(with:completionHandler:)`](/documentation/Foundation/URLSession/dataTask(with:completionHandler:)-52wk8)

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

[`dataTask(with:)`](/documentation/Foundation/URLSession/dataTask(with:)-7jpys)

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

[`dataTask(with:completionHandler:)`](/documentation/Foundation/URLSession/dataTask(with:completionHandler:)-e6xv)

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

[`URLSessionDataTask`](/documentation/Foundation/URLSessionDataTask)

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

[`URLSessionDataDelegate`](/documentation/Foundation/URLSessionDataDelegate)

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

### Adding download tasks to a session

[`downloadTask(with:)`](/documentation/Foundation/URLSession/downloadTask(with:)-1onj)

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

[`downloadTask(with:completionHandler:)`](/documentation/Foundation/URLSession/downloadTask(with:completionHandler:)-7cuje)

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

[`downloadTask(with:)`](/documentation/Foundation/URLSession/downloadTask(with:)-3fb7s)

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.

[`downloadTask(with:completionHandler:)`](/documentation/Foundation/URLSession/downloadTask(with:completionHandler:)-4a84s)

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.

[`downloadTask(withResumeData:)`](/documentation/Foundation/URLSession/downloadTask(withResumeData:))

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

[`downloadTask(withResumeData:completionHandler:)`](/documentation/Foundation/URLSession/downloadTask(withResumeData:completionHandler:))

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

[`URLSessionDownloadTask`](/documentation/Foundation/URLSessionDownloadTask)

A URL session task that stores downloaded data to a file.

[`URLSessionDownloadDelegate`](/documentation/Foundation/URLSessionDownloadDelegate)

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

### Adding upload tasks to a session

[Building a resumable upload server with SwiftNIO](/documentation/Foundation/building-a-resumable-upload-server-with-swiftnio)

Support HTTP resumable upload protocol in SwiftNIO by translating resumable uploads to regular uploads.

[`uploadTask(with:from:)`](/documentation/Foundation/URLSession/uploadTask(with:from:))

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

[`uploadTask(with:from:completionHandler:)`](/documentation/Foundation/URLSession/uploadTask(with:from: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.

[`uploadTask(with:fromFile:)`](/documentation/Foundation/URLSession/uploadTask(with:fromFile:))

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

[`uploadTask(with:fromFile:completionHandler:)`](/documentation/Foundation/URLSession/uploadTask(with:fromFile:completionHandler:))

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

[`uploadTask(withStreamedRequest:)`](/documentation/Foundation/URLSession/uploadTask(withStreamedRequest:))

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

[`uploadTask(withResumeData:)`](/documentation/Foundation/URLSession/uploadTask(withResumeData:))

Creates an upload task from a resume data blob. Requires the server to support the latest resumable uploads
Internet-Draft from the HTTP Working Group, found at
https://datatracker.ietf.org/doc/draft-ietf-httpbis-resumable-upload/
If resuming from an upload file, the file must still exist and be unmodified. If the upload cannot be successfully
resumed, URLSession:task:didCompleteWithError: will be called.

[`uploadTask(withResumeData:completionHandler:)`](/documentation/Foundation/URLSession/uploadTask(withResumeData:completionHandler:))

Creates a URLSessionUploadTask from a resume data blob. If resuming from an upload
file, the file must still exist and be unmodified.

[`URLSessionUploadTask`](/documentation/Foundation/URLSessionUploadTask)

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

[`URLSessionDataDelegate`](/documentation/Foundation/URLSessionDataDelegate)

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

### Adding stream tasks to a session

[`streamTask(withHostName:port:)`](/documentation/Foundation/URLSession/streamTask(withHostName:port:))

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

[`streamTask(with:)`](/documentation/Foundation/URLSession/streamTask(with:))

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

[`URLSessionStreamTask`](/documentation/Foundation/URLSessionStreamTask)

A URL session task that is stream-based.

[`URLSessionStreamDelegate`](/documentation/Foundation/URLSessionStreamDelegate)

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

### Adding WebSocket tasks to a session

[`webSocketTask(with:)`](/documentation/Foundation/URLSession/webSocketTask(with:)-87ipz)

Creates a WebSocket task for the provided URL.

[`webSocketTask(with:)`](/documentation/Foundation/URLSession/webSocketTask(with:)-mtks)

Creates a WebSocket task for the provided URL request.

[`webSocketTask(with:protocols:)`](/documentation/Foundation/URLSession/webSocketTask(with:protocols:))

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

[`URLSessionWebSocketTask`](/documentation/Foundation/URLSessionWebSocketTask)

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

[`URLSessionWebSocketDelegate`](/documentation/Foundation/URLSessionWebSocketDelegate)

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

[`NSURLSessionWebSocketMessage`](/documentation/Foundation/NSURLSessionWebSocketMessage)

[`NSURLSessionWebSocketMessageType`](/documentation/Foundation/NSURLSessionWebSocketMessageType)

An enumeration of the types of messages sent and received.

### Managing the session

[`finishTasksAndInvalidate()`](/documentation/Foundation/URLSession/finishTasksAndInvalidate())

Invalidates the session, allowing any outstanding tasks to finish.

[`flush(completionHandler:)`](/documentation/Foundation/URLSession/flush(completionHandler:))

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

[`getTasksWithCompletionHandler(_:)`](/documentation/Foundation/URLSession/getTasksWithCompletionHandler(_:))

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

[`getAllTasks(completionHandler:)`](/documentation/Foundation/URLSession/getAllTasks(completionHandler:))

Asynchronously calls a completion callback with all tasks in a session

[`invalidateAndCancel()`](/documentation/Foundation/URLSession/invalidateAndCancel())

Cancels all outstanding tasks and then invalidates the session.

[`reset(completionHandler:)`](/documentation/Foundation/URLSession/reset(completionHandler:))

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

[`sessionDescription`](/documentation/Foundation/URLSession/sessionDescription)

An app-defined descriptive label for the session.

### Handling errors

[URL session error dictionary keys](/documentation/Foundation/url-session-error-dictionary-keys)

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

[Background task cancellation](/documentation/Foundation/background-task-cancellation)

Constants that indicate why a background task was canceled.

### Performing tasks as a Combine Publisher

[Processing URL session data task results with Combine](/documentation/Foundation/processing-url-session-data-task-results-with-combine)

Use a chain of asynchronous operators to receive and process data fetched from a URL.

[`dataTaskPublisher(for:)`](/documentation/Foundation/URLSession/dataTaskPublisher(for:)-61v3e)

Returns a publisher that wraps a URL session data task for a given URL request.

[`dataTaskPublisher(for:)`](/documentation/Foundation/URLSession/dataTaskPublisher(for:)-5kiir)

Returns a publisher that wraps a URL session data task for a given URL.

[`URLSession.DataTaskPublisher`](/documentation/Foundation/URLSession/DataTaskPublisher)

A publisher that delivers the results of performing URL session data tasks.

### Deprecated

[`new()`](/documentation/Foundation/URLSession/new())

[`init()`](/documentation/Foundation/URLSession/init())



---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)
