Using URLSession with async/await in Swift
Learn how to make HTTP networking requests with URLSession's async/await API.
17 Oct 2022 · 3 min read
Along with the release of async/await in Swift 5.5, Apple has also extended many of their asynchronous APIs to support the async/await concurrency model.
In this article, we'll look at how to use async/await methods for URLSession to send requests or to download and upload data to a server.

Sending a URL request
When working with URLSession, we can use the URLSessionDataTask type to send requests and receive responses.
Prior to Swift's async/await feature, completion handlers or delegates were the standard pattern to use. Sending a request by using a completion handler looks as follows:
let task = URLSession.shared.dataTask(with: urlRequest) { data, response, error in// Handle response.}task.resume()
With async/await, the same can be done in one line:
let (data, response) = try await URLSession.shared.data(for: urlRequest)
Downloading data
A download request works almost the same as the request we looked at above with the only difference that we get a file url instead of a data object as a response.
With a completion handler, a download request looks as follows:
let task = URLSession.shared.downloadTask(with: url) { fileURL, response, error in// Handle response}task.resume()
When using async/await, the same request can also be reduced to one line:
let (fileURL, response) = try await URLSession.shared.download(from: url)
Uploading data
When uploading data to a server, we can either pass in a Data object or a file url.
With a completion handler, an upload request looks as follows:
let task = urlSession.uploadTask(with: urlRequest, from: data) { data, response, error in// Handle response}task.resume()
When using async/await, the same request can also be reduced to one line:
let (data, response) = try await URLSession.shared.upload(for: urlRequest)

Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips