---
title: URLSession
framework: foundation
role: symbol
role_heading: Class
path: foundation/urlsession
---

# URLSession

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

## Declaration

```swift
class URLSession
```

## Mentioned in

Pausing and resuming uploads Analyzing HTTP traffic with Instruments Processing URL session data task results with Combine Downloading files from websites Downloading files in the background Fetching website data into memory Uploading data to a website Improving network reliability using Multipath TCP Pausing and resuming downloads Performing manual server trust authentication Uploading streams of data

## Overview

Overview The 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 and URLSessionTaskDelegate to support authentication and receive events like redirection and task completion. note: The 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 URL Loading System topic. The articles in the Essentials, Uploading, and Downloading sections offer examples of performing common tasks with URLSession. Your app creates one or more 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 has a singleton 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 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 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 objects in memory. The URLSession API provides four types of tasks: Data tasks send and receive data using 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. 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. You can also intercept these callbacks before they reach the session delegate by populating a separate delegate that’s specific to the task. Asynchronicity and URL sessions Like most networking APIs, the 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, data(from:delegate:) fetches data, while download(from:delegate:) downloads files. Your call point uses the await keyword to suspend running until the transfer completes. You can also use the bytes(from:delegate:) method to receive data as an AsyncSequence. With this approach, you use the for-await-in syntax to iterate over the data as your app receives it. The 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 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 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 supports the HTTP/1.1, HTTP/2, and HTTP/3 protocols. HTTP/2 support, as described by RFC 7540, 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. 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. ATS requires that HTTP connections use HTTPS (RFC 2818). For more information, see NSAppTransportSecurity. Foundation copying 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 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](foundation/urlsession/shared.md)

### Creating a session

- [init(configuration:)](foundation/urlsession/init(configuration:).md)
- [init(configuration:delegate:delegateQueue:)](foundation/urlsession/init(configuration:delegate:delegatequeue:).md)
- [URLSessionConfiguration](foundation/urlsessionconfiguration.md)
- [configuration](foundation/urlsession/configuration.md)

### Working with a delegate

- [delegate](foundation/urlsession/delegate.md)
- [URLSessionDelegate](foundation/urlsessiondelegate.md)
- [URLSessionTaskDelegate](foundation/urlsessiontaskdelegate.md)
- [delegateQueue](foundation/urlsession/delegatequeue.md)

### Performing asynchronous transfers

- [bytes(for:delegate:)](foundation/urlsession/bytes(for:delegate:).md)
- [bytes(from:delegate:)](foundation/urlsession/bytes(from:delegate:).md)
- [URLSession.AsyncBytes](foundation/urlsession/asyncbytes.md)
- [data(for:delegate:)](foundation/urlsession/data(for:delegate:).md)
- [data(from:delegate:)](foundation/urlsession/data(from:delegate:).md)
- [data(for:)](foundation/urlsession/data(for:).md)
- [data(from:)](foundation/urlsession/data(from:).md)
- [download(for:delegate:)](foundation/urlsession/download(for:delegate:).md)
- [download(from:delegate:)](foundation/urlsession/download(from:delegate:).md)
- [download(resumeFrom:delegate:)](foundation/urlsession/download(resumefrom:delegate:).md)
- [upload(for:from:delegate:)](foundation/urlsession/upload(for:from:delegate:).md)
- [upload(for:fromFile:delegate:)](foundation/urlsession/upload(for:fromfile:delegate:).md)
- [upload(for:from:)](foundation/urlsession/upload(for:from:).md)
- [upload(for:fromFile:)](foundation/urlsession/upload(for:fromfile:).md)
- [URLSessionTaskDelegate](foundation/urlsessiontaskdelegate.md)

### Adding data tasks to a session

- [dataTask(with:)](foundation/urlsession/datatask(with:)-10dy7.md)
- [dataTask(with:completionHandler:)](foundation/urlsession/datatask(with:completionhandler:)-52wk8.md)
- [dataTask(with:)](foundation/urlsession/datatask(with:)-7jpys.md)
- [dataTask(with:completionHandler:)](foundation/urlsession/datatask(with:completionhandler:)-e6xv.md)
- [URLSessionDataTask](foundation/urlsessiondatatask.md)
- [URLSessionDataDelegate](foundation/urlsessiondatadelegate.md)

### Adding download tasks to a session

- [downloadTask(with:)](foundation/urlsession/downloadtask(with:)-1onj.md)
- [downloadTask(with:completionHandler:)](foundation/urlsession/downloadtask(with:completionhandler:)-7cuje.md)
- [downloadTask(with:)](foundation/urlsession/downloadtask(with:)-3fb7s.md)
- [downloadTask(with:completionHandler:)](foundation/urlsession/downloadtask(with:completionhandler:)-4a84s.md)
- [downloadTask(withResumeData:)](foundation/urlsession/downloadtask(withresumedata:).md)
- [downloadTask(withResumeData:completionHandler:)](foundation/urlsession/downloadtask(withresumedata:completionhandler:).md)
- [URLSessionDownloadTask](foundation/urlsessiondownloadtask.md)
- [URLSessionDownloadDelegate](foundation/urlsessiondownloaddelegate.md)

### Adding upload tasks to a session

- [Building a resumable upload server with SwiftNIO](foundation/building-a-resumable-upload-server-with-swiftnio.md)
- [uploadTask(with:from:)](foundation/urlsession/uploadtask(with:from:).md)
- [uploadTask(with:from:completionHandler:)](foundation/urlsession/uploadtask(with:from:completionhandler:).md)
- [uploadTask(with:fromFile:)](foundation/urlsession/uploadtask(with:fromfile:).md)
- [uploadTask(with:fromFile:completionHandler:)](foundation/urlsession/uploadtask(with:fromfile:completionhandler:).md)
- [uploadTask(withStreamedRequest:)](foundation/urlsession/uploadtask(withstreamedrequest:).md)
- [uploadTask(withResumeData:)](foundation/urlsession/uploadtask(withresumedata:).md)
- [uploadTask(withResumeData:completionHandler:)](foundation/urlsession/uploadtask(withresumedata:completionhandler:).md)
- [URLSessionUploadTask](foundation/urlsessionuploadtask.md)
- [URLSessionDataDelegate](foundation/urlsessiondatadelegate.md)

### Adding stream tasks to a session

- [streamTask(withHostName:port:)](foundation/urlsession/streamtask(withhostname:port:).md)
- [streamTask(with:)](foundation/urlsession/streamtask(with:).md)
- [URLSessionStreamTask](foundation/urlsessionstreamtask.md)
- [URLSessionStreamDelegate](foundation/urlsessionstreamdelegate.md)

### Adding WebSocket tasks to a session

- [webSocketTask(with:)](foundation/urlsession/websockettask(with:)-87ipz.md)
- [webSocketTask(with:)](foundation/urlsession/websockettask(with:)-mtks.md)
- [webSocketTask(with:protocols:)](foundation/urlsession/websockettask(with:protocols:).md)
- [URLSessionWebSocketTask](foundation/urlsessionwebsockettask.md)
- [URLSessionWebSocketDelegate](foundation/urlsessionwebsocketdelegate.md)

### Managing the session

- [finishTasksAndInvalidate()](foundation/urlsession/finishtasksandinvalidate().md)
- [flush(completionHandler:)](foundation/urlsession/flush(completionhandler:).md)
- [getTasksWithCompletionHandler(_:)](foundation/urlsession/gettaskswithcompletionhandler(_:).md)
- [getAllTasks(completionHandler:)](foundation/urlsession/getalltasks(completionhandler:).md)
- [invalidateAndCancel()](foundation/urlsession/invalidateandcancel().md)
- [reset(completionHandler:)](foundation/urlsession/reset(completionhandler:).md)
- [sessionDescription](foundation/urlsession/sessiondescription.md)

### Handling errors

- [URL session error dictionary keys](foundation/url-session-error-dictionary-keys.md)
- [Background task cancellation](foundation/background-task-cancellation.md)

### Performing tasks as a Combine Publisher

- [Processing URL session data task results with Combine](foundation/processing-url-session-data-task-results-with-combine.md)
- [dataTaskPublisher(for:)](foundation/urlsession/datataskpublisher(for:)-61v3e.md)
- [dataTaskPublisher(for:)](foundation/urlsession/datataskpublisher(for:)-5kiir.md)
- [URLSession.DataTaskPublisher](foundation/urlsession/datataskpublisher.md)

### Deprecated

- [new()](foundation/urlsession/new().md)
- [init()](foundation/urlsession/init().md)

## Relationships

### Inherits From

- [NSObject](objectivec/nsobject-swift.class.md)

### Conforms To

- [CVarArg](swift/cvararg.md)
- [CustomDebugStringConvertible](swift/customdebugstringconvertible.md)
- [CustomStringConvertible](swift/customstringconvertible.md)
- [Equatable](swift/equatable.md)
- [Hashable](swift/hashable.md)
- [NSObjectProtocol](objectivec/nsobjectprotocol.md)
- [Sendable](swift/sendable.md)
- [SendableMetatype](swift/sendablemetatype.md)

## See Also

### Essentials

- [Fetching website data into memory](foundation/fetching-website-data-into-memory.md)
- [Analyzing HTTP traffic with Instruments](foundation/analyzing-http-traffic-with-instruments.md)
- [URLSessionTask](foundation/urlsessiontask.md)
