Episode #510

Async Networking

Series: Async / Await

6 minutes
Published on November 5, 2021

This video is only available to subscribers. Get access to this video and 584 others.

In this episode we will see how URLSession can be used with async await. With this new API you can easily send network request and await a tuple of both the data and the response object.
func downloadThumbnail(_ url: URL) async throws -> UIImage {
    let session = URLSession.shared

    // simulate a longer delay        
    await Task.sleep(NSEC_PER_SEC)

    let (data, response) = try await session.data(from: url, delegate: nil)

    guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
        throw UnexpectedResponse()
    }

    guard let image = UIImage(data: data) else {
        throw InvalidImage()
    }

    return image
}

This episode uses Xcode 13.0, Swift 5.5.