Member-only story
Making Network Requests With Async/Await in Swift
Power up your iOS apps with Swift concurrency
Traditionally, when we want to make a network request, we must use the closure-based URLSession
APIs to perform the request asynchronously so that our apps can be responsive while waiting for it to complete. With the release of Swift 5.5, this is no longer the case, we now have another alternative which is to use async/await.
In this article, I would like to show you how to make a network request by using the async/await keywords. On top of that, I will also do a quick comparison between async/await and closure-based API so that you can better understand the benefits of using async/await.
This article does require you to have a basic understanding of async/await. Therefore, if you’re unfamiliar with Swift concurrency, I highly encourage you to first read my blog post called “Getting Started with Swift Concurrency.”
With all that being said, let’s get right into it!
Prerequisite
Throughout this article, we will be using the Apple iTunes API to fetch a collection of albums from Taylor Swift. Following is the API’s URL:
https://itunes.apple.com/search?term=taylor+swift&entity=album
This API endpoint will give us the following JSON response:
For demonstration purposes, we will grab the album’s name and price and show them on a collection view list. Here are the model objects that we need for JSON decoding:
Note that we are conforming the Album
struct to the Hashable
protocol so that we can use it as our collection view diffable data source’s item identifier type.
With all that out of the way, let’s get into the network requests code.