Networking in SwiftUI with Async/Await
How to build a networking client in Swift using Async/Await and integrating it easily with SwiftUI!
Remember two years ago when almost every new project relied on a library for networking else the pyramid of doom would take over? URLSession completion handlers were too clunky, so we used libraries like Alamofire to provide an easy-to-use API for creating requests. With the recent additions to
URLSession, 3rd party libraries seem like overkill for practical use cases.
In the recent release of Xcode 13, we received more updates to
URLSession. The biggest being support for async/await. What exactly is it?
At a high level, they are new keywords added to Swift to specify when code needs to be run asynchronously, and we need to wait without blocking the thread. Let's look at a simple example.
Taskenables us to run background tasks concurrently async
Awaitfrees up the thread until the data task returns
- Finally, the data is decoded and assigned to a property (on the main thread)
Now that you've seen a basic example, how can we use async/await to build a small networking library? To begin, let's start with defining and constructing an endpoint. Then create a view model responsible for initiating the request and returning an async result for the UI.
In this example, we'll be fetching restaurant data from the Yelp API. It's free to use, and if you want to follow along, sign up for an API key here. I'll also mention that I released a mini YouTube series around building a similar app. If that sparks your interest, check it out on my channel.
First, let start defining our endpoints and building the necessary URL components to create an API request. We'll use an enum, where each case is a different endpoint on our API.