Networking in Swift
I’ve recently started my path in IOS development and decided to write a quick tutorial. This article focuses on one of the first things you'll learn when building an app, creating API requests.
Before I dive in though, let’s talk about what the heck an API is in the first place. API stands for Application Programming Interface. Now, if you’re like me , you’re probably saying “… and what does that mean to me?!”.
APIs allow outside devs access to companies app data to manipulate for their own use. Companies have documentation on the specific URL string thats required to access their data along with an API Key. This key is whats grants you access to the API and is unique to you.
Think of an API like a contract, the documentation that represents an agreement between 2 parties. If party 1 sends a remote request structured a particular way, then party 2’s software will respond.
Okay, enough of the explanation. Let’s start building our URL string so we can actually make our API request. We will be using the movieDB API for the following examples.
Creating the Struct
First let us take a look at the data we want to grab. We will be using the movieDB’s API and we’re looking for movies that are “Now Playing”.
API Docs
Hosted API documentation for every OAS (Swagger) and RAML spec out there. Powered by Stoplight.io. Document, mock…
developers.themoviedb.org
Below shows how our URL string should look as well as what the JSON response data will look like. It also details what data types to use in our struct which will be used to decode the JSON.
the movieDB schema
The JSON response
Let’s go ahead and create the structs needed to decode the JSON.
Our struct must first conform to the Decodable protocol and each property must match the keys from the JSON response (Use the pic above to determine what type each property should be). Usually, JSON response keys are snake case. As in they look like this: “vote_average”. By default Decodable converts snake case to CamelCase which is the common convention in Swift. So a struct that has a property of let voteAverage will successfully parse the JSON key “vote_average”.
Something to be aware of is this JSON response returns an array of movies objects. Our struct has to mirror this, which is shown in the struct seen above. Also what I did here was initialize all the properties as optional values in case the JSON response for that property is nil. We don’t want the the app to crash because the property is nil.
Creating the URL String
The image above reflects using a computed property to create and store our URL string.
This will give you is an an URL that looks like this:
https://api.themoviedb.org/3/movie/now_playing?api_key=b4b16ea1d5df4aabad5fd38c349df7d8
Creating and executing the request
Now that we have the appropriate endpoint set up and are ready to go. We have set up the request to the movieDB’s Server. To do so we will have to use URLSession.
Okay! Now let’s break down this code:
To make the request we have to make use of URLSession, a class in the Swift language that lets us make url requests. Set this as a variable.
Next, create another variable which will hold the actual request, we usually call this task. The dataTask takes in 2 parameters: The URL String and closure also called a completion handler(executes when the request completes, hence the name). The completion handler contains 3 parameters: data, response, error. All of which can be nil because they are all optionals.
Data: The data object that is being returned. In this case it’ll be the JSON object.
Response: This will be the response code we’re receiving. Think https status codes like 200 as a success and 400 as a failure.
Error: If an error occurred while trying to retrieve JSON. An error will throw if everything went A-okay then this will be nil.
We already constructed our Url string so we won’t need to worry about that now. We can just pop the variable inside the function as the first argument. Now let’s focus on the second parameter.
Our request is all set up, now me must send it off. By default, data tasks are are paused. If we want to execute the request we must use task.resume.
task.resume
Now that the request is sent off we have to check for errors. We check if an error actually contains an error (so making sure its nil), and if so then we’ll go about decoding our JSON response into a struct that swift can work with. Which in this case is our NowPlaying Struct.
There, that’s it! We have successfully made a network request!
In Summary:
To make a network request in Swift:
Figure out the API you want to use and read up on the documentation to learn how to use it.
Create the structs needed to Decode the JSON response.
Build the URL string
Create and initiate the request using task.resume.