0% found this document useful (0 votes)
67 views2 pages

API Layer in Swift With Async:Await - Better Programming

Uploaded by

9y8b8pbcdj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views2 pages

API Layer in Swift With Async:Await - Better Programming

Uploaded by

9y8b8pbcdj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Search Medium Write Sign up Sign In

Build a Modern Networking Layer in


Swift Using Async/Await
An Async/Await API layer to help you ace live coding interviews

Jonathon Albert · Follow


Published in Better Programming · 6 min read · Oct 3, 2022

152 1

Image by Firmbee from Pixabay

A common requirement in iOS developer live coding interviews is being able


to implement networking layers from scratch within a set time frame. While
it may not come up often when working professionally as most apps will
already contain an established network layer, knowing how to build one
quickly when wanting to prototype something is incredibly useful.

I want to demonstrate a quick and easy network layer you can use to ace live
coding interviews, it conforms to SOLID principles, uses generics,
implements Async/Await, has appropriate error handling, works in UIKit and
SwiftUI apps and if you practice writing it from scratch, can be up and
running within 10 minutes which leaves you more time in a technical
interview to focus on the rest of the functionality.

Let’s get started!

First of all, we’ll need an API to pull data from, preferably something with a
couple of different endpoints that return different types of data. The UK
government’s food hygiene rating API is a good starting point.

Take some time to familiarise yourself with it, but it’s not crucial to know it
as we’ll be looking at a couple of the endpoints in particular as part of this
guide.

On to some coding:

We’ll start coding the APIRouter with an enum to act as our router object
which will house the components needed to construct each of our requests.
For this guide, we’ll be creating 3 different requests:

1. getAuthorities — Returns details of the different authorities (read:


regions) within the UK

2. getRatings — Returns details on the rating systems used by food


hygiene authorities

3. getEstablishments — Returns the details of establishments, we’ll be


passing an ID to this to return establishments within a specific
authority (region)

We’re going to be turning the components we set up in this enum into


URLComponents later on as part of the APIRequestDispatcher but we need a
few things:

1. host — This is the common root of your API requests, think


medium.com

2. scheme — This is your API’s web server protocol (HTTP / HTTPS)

3. path — This is the specific resource endpoint we’re requesting, think


{host}/@soaringearth

4. method — The API method that you’re using to make the request
(POST/PUT/PATCH/GET/DELETE)

5. parameters — These are any query parameters you want to send to


the API

You might notice I’ve not covered body objects, I’ve never been asked
personally to implement POST requests during interviews, this will be due to
the additional time to set up and configure compared to more simple GET

requests. If we did want to add body data, it would be added as part of the
URLRequestDispatcher as URLComponents in iOS only deal with the construction
of URLs (which seems obvious) — It would be the URLRequest objects to
which we need to add data to.

You’ll see the complete router above, which matches what was discussed
previously. You might wonder why we decided to use an enum , and it’s for
quite a simple reason. If we decide to add a 4th request, the compiler will
throw errors within each computed variable to indicate we are missing a
handled case, which prevents you from forgetting to implement its
scheme/path/method etc.

A note regarding the APIRouter — since I mentioned SOLID principles,


having a single router that holds all the components for every request the
application wants to make doesn’t quite sit well with the single responsibility
principle, in a production app you might want to consider having different
routers for each endpoint if you have multiple paths per endpoint i.e
(/ratings, /ratings/{id}, /ratings/{id}/xxxYYY), but keeping the context of this
guide in mind which is the ability to produce something within a time-
limited technical interview, the approach in this guide will be more than
sufficient.

We’re now moving on to the APIRequestDispatcher . This is probably the most


complicated aspect of the guide and contains some features that you might
not be familiar with, namely generics and async/await which I’ll include
some links to the documentation:

Generics: https://docs.swift.org/swift-
book/LanguageGuide/Generics.html

Async/Await: https://docs.swift.org/swift-
book/LanguageGuide/Concurrency.html

There will be an element of custom error handling as well but that’s pretty
easy to see what’s going on.

The class itself will be straightforward and only contain a single class
function request<T: Codable>(router: APIRouter) async throws -> T . For most
cases, it will be more than sufficient to handle simple API requests. Breaking
it down, you can see it expects and will return objects that conform to the
codable protocol, you need to provide an APIRouter as a parameter, the
function runs asynchronously, and can also throw errors.

Let’s break down the snippet above:

1. The URLComponent is what we’ll construct based on the enum we


created previously and why we need to pass in an APIRouter to the
function.

2. URLComponent contains a property that allows you to get an optional


URL back which will return nil if the URL cannot be constructed
based on the various components it has set. We also want to throw a
custom error here if we fail to get the complete URL.

3. This is a nuance of the Food Hygiene API, it requires all requests to


contain a x-api-version header, you wouldn’t need this with other
APIs.

4. try await withCheckedThrowingContinuation { continuation — This is


an Async/Await function which suspends the current task and calls
the closure with a checked throwing continuation which is a fancy way
of saying that it's a closure that can be called with the result of
asynchronous work. The contents of the closure are mostly the same
as regular URLSession requests.

5. If our dataTask fails to get any data back, we can throw our other
custom error here to indicate a noData response, handling the error
appropriately.

6. DispatchQueue.main.async will return us onto the main thread.

7. The main difference with using Async/Await is instead of just


returning, we need to call continuation.resume(with: and provide our
result (success/failure).

That’s pretty much it for the request dispatcher, our generics are decoded
and returned, and any errors are handled and thrown accordingly.

Creating custom errors are as simple as defining a new enum:

The API Clients that we’ll make are how the users/apps interactions will
communicate with the API. We will create 1 client per request using a POP
(Protocol Oriented Programming) approach. Each request will have its own
protocol and a class that conforms to it, we do it this way for ease of mocking
the API Client and better separation of concerns as some screens may only
want to access a list of authorities, whereas others may only want ratings.

You can see the implementations above, you might notice that with the
RatingClient we pass a parameter but not to the router, this is because
there’s a limitation in the API, the rating endpoint doesn’t accept and query
parameters so filtering has to be done on the device.

The model objects used within this implementation are simple to


understand, they are basic structs that conform to codable. For improved
readability when using the objects there are a couple CodingKeys that have
been used which translate the key of the object received to the name of the
property present within the model object. More info can be found here

Finally, here’s an example of how to actually fetch data using the


Async/Await approach. It’s just a case of wrapping the API requests inside
Task.init and using a do/catch to handle the errors.

Thanks for reading I do hope everything was clearly explained and


understandable, I used this approach in several interviews and once you’ve
practiced it a few times you can genuinely have the API Layer written in
around 10 minutes if not less. If you have questions about this guide or
interviewing for iOS roles in general feel free to reach out.

IOS Swift Programming Concurrency Software Development

152 1

Written by Jonathon Albert Follow

82 Followers · Writer for Better Programming

iOS app developer, team lead, passionate about building and fostering a team culture that
keeps people engaged

More from Jonathon Albert and Better Programming

Jonathon Albert in Better Programming Benoit Ruiz in Better Programming

Setting Up Live Activities for the Advice From a Software Engineer


Dynamic Island in iOS 16 With 8 Years of Experience
Start, fetch, update, and end live activities Practical tips for those who want to advance
in their careers

5 min read · Oct 7, 2022 22 min read · Mar 21

203 1 6.7K 129

Dmitry Kruglov in Better Programming Jonathon Albert in Better Programming

The Architecture of a Modern Implement Firebase Push


Startup Notifications in Swift
Hype wave, pragmatic evidence vs the need Push notifications are the best tool to
to move fast increase user engagement inside and outsid…
your app
16 min read · Nov 7, 2022 9 min read · Oct 17, 2022

5.5K 48 23

See all from Jonathon Albert See all from Better Programming

Recommended from Medium

Joliph Christian in Simform Engineering Derek Kim in AWS Tip

Handling Network calls in Swift Effective Ways to Call Endpoints:


with Moya Part 2— Swift | iOS Tutorial
It’s a powerful network tool that meets your Hello this is Noobie!
needs!

5 min read · Apr 18 5 min read · Apr 14

436

Lists

General Coding Knowledge It's never too late or early to


20 stories · 298 saves start something
15 stories · 105 saves

Coding & Development Stories to Help You Grow as a


11 stories · 151 saves Software Developer
19 stories · 341 saves

Finsi Ennes in Level Up Coding Eyup Yasuntimur

Adopt Async-Await in your project Migrating Networking Callbacks to


Step by step Async/Await
Hello everybody!
· 6 min read · Nov 7, 2022 5 min read · Jul 10

85 1 10

Hemal Asanka Lakshminaidu C

Making API calls with iOS Combine Class vs Struct vs Actor


Future Publisher
What Is the Combine Framework?

8 min read · May 5 4 min read · Jul 21

16 173 3

See more recommendations

Help Status Writers Blog Careers Privacy Terms About Text to speech Teams

You might also like