Logo for tanaschita.com

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.

Sponsorship logo
Join the FREE iOS Architect Crash Course (for a limited time!)
If you’re a mid/senior iOS developer who’s looking to improve both your skills and salary level, then join this 100% free online crash course. Hurry up because it's available only until November 27th!
Click to get it now

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)
Sponsorship logo
Join the FREE iOS Architect Crash Course (for a limited time!)
If you’re a mid/senior iOS developer who’s looking to improve both your skills and salary level, then join this 100% free online crash course. Hurry up because it's available only until November 27th!
Click to get it now

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

async/await

concurrency

swift

Memory management for async/await and tasks in Swift

Learn about weak self references when working with the async/await API.

03 Oct 2022 · 2 min read

Latest articles and tips

© 2022 tanaschita.com

Privacy policy

Impressum