Better Programming

Advice for programmers.

Follow publication

Member-only story

Making Network Requests With Async/Await in Swift

Lee Kah Seng
Better Programming
Published in
7 min readAug 26, 2021
Neon lines
Photo by Federico Beccari on Unsplash

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:

JSON response from Apple iTunes API
JSON response from Apple iTunes API

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.

The Traditional Way

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Lee Kah Seng
Lee Kah Seng

Written by Lee Kah Seng

Support me by becoming a Medium member: https://leekahseng.medium.com/membership ⦿ 🇲🇾 Creator of https://swiftsenpai.com ⦿ iOS developer since 2011

No responses yet

Write a response