Use async/await with URLSession

With a real example

Steven Curtis
2 min readJul 2, 2021

Before we start

Difficulty: Beginner | Easy | Normal | Challenging

This article has been developed using Xcode 13, and Swift 5.5.

If you’d like to see a video version of this article, follow this link: https://youtu.be/ZurWIRpX_HA, all the code is in the GitHub repo

Keywords and Terminology

async/await: An alternative to completion handlers, a coroutine model that allows execution to be suspended and resumed
URLSession: The class and related classes proved an API for downloading data to and from endpoints indicated by URLs

This article

Background

I’ve got “Standard” use of URSession, using a view controller, view model and a closure to return the result.

Can I convert this to use Apple’s new async/await? I sure can — and this adds a real example to the relevant WWDC video.

The URL I’ll be using is https://reqres.in/api/users?page=2, which is always a good site to use for example Apps requesting and returning JSON.

Note that each of these projects only do one thing. That is, they both write the result to the console (there is…

--

--

No responses yet