Getting Started with Async/Await in iOS

Mohammad Azam
4 min readJun 9, 2021
Photo by Matt Duncan on Unsplash

When working with asynchronous code we often leverage the use of callbacks so we can execute code when the asynchronous operation finishes. This works fine in simple scenarios but gets complicated if we have to perform a future request based on the result of the previous request. The callback pattern also open doors for not remembering to execute the user interface code on the main thread, which can lead to performance issues.

Swift 5.5 includes a new way of performing asynchronous actions. This is done by the support of async/await feature. In this article we will look at how you can get started with using async/await in your iOS applications.

Stocks App

Movies App Gist

Invoking Movies API Using Callbacks

Before jumping into the async/await details, let’s take a look at how we currently fetch data from an API using callbacks. For this example we will be using the OMDB API to fetch a list of movies. The code below shows the getMovies function inside the Webservice class, which is responsible for making a network call and fetching all the movies from the OMDB API.

The Result enum allows us to classify the response as success or failure. There are couple of things worth noting about the above code. First, we need to make sure that we access the completion on the main thread as we need to update the user interface. We also need to make sure to return from each of the guard statements. And finally, if we had to make another call which is dependent on the first call then it will become more complicated as we will have to nest the second call within the success handler of the first call.

Now, let’s try to implement the same network call using the async/await approach.

Mohammad Azam

iOS Developer, speaker and educator. Top Udemy and LinkedIn instructor. Lead instructor at DigitalCrafts. https://www.udemy.com/user/mohammad-azam-2/

Recommended from Medium

Lists