Using URLSession to retrieve JSON in Swift (1) - Getting Started

“A young blonde woman looking at Elvis Presley's vinyl record in a record store” by Jamakassi on Unsplash

This article is to demonstrate how to retrieve JSON data from a HTTP Web API in iOS development.

Mobile apps and Web apps nowadays most likely need to fetch information from the internet and to display them. It is very common usage, if not inevitable, of modern apps.

We will start from understanding the basic usage of URLSession in Swift firstly. And then try to make that into practice. Finally we will try to get data from Unsplash and model it as a real world example.

If you are not familiar with starting a new Xcode project or starting any iOS development. It would be greatly appreciated if you can visit any of my previous tutorials before getting started.

Xcode Starter Guide (1) — Learn How To Use Xcode

Xcode Starter Guide (2) — Run Your First App

Xcode Starter Guide (3) — Common Practices to Start an iOS App with CocoaPods

You may need some basic understanding of Xcode, Swift programming language, Optionals and Protocols.

The source code of this tutorial is available on Github.

Let's start the journey. Hope you enjoy it!

URLSession vs Alamofire

In the start of the very beginning timeline of iOS development, there is always a networking 3rd party library for developers to use over the native one. The most popular one was AFNetworking (which is Alamofire in Swift). It was extremely popular back in the Objective-C days.

iOS development runs as a routine that we initialize the project with Cocoapods, installing libraries like AFNetworking as a standard. There are a lot of pros and cons to discuss with towards this routine. Like NSURLConnection was painful to deal with or AFNetworking easily fall into breaking changes when doing Cocoapods upgrade etc.

Vanilla URLSession

The one thing we should know over the years that URLSession has become more and more friendly to use to grab JSON data with Codable introduced in Swift 4 and it is more than enough for practical use.

So this will be an demonstration using URLSession. And we are not going to investigate which approach, URLSession or Alamofire, is good or bad in this article.

Let's Get Started

We will start from creating a playground in Xcode.

If we need to fetch JSON data from an API, first we need that API. We can manually declare APIs using any JSON object uploading to myjson or any similar services.

Let’s say we declare the JSON object as below.

{ 
"foo": "bar"
}

And we can generate an URL accessing this JSON data. In my example, it is https://api.myjson.com/bins/yfua8. If my link is not valid, you should create one of your own.

Back to the playground, we can create the URL of this API.

if let url = URL(string: "https://api.myjson.com/bins/yfua8") {
// the url
}

For URL tasks to be working in playground, we also need to include some support before the code.

import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

Then we can retrieve data from the url.

if let url = URL(string: "https://api.myjson.com/bins/yfua8") {
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
if let jsonString = String(data: data, encoding: .utf8) {
print(jsonString)
}
}
}.resume()
}

The quickest way to visualize whether we are successful of not is to convert the data received to a string and display it. So, in your console, you should see somthing like below.

{"foo":"bar"}

And we have successful received the data. This is a string representation of our API response. We receive the JSON with Data format. And convert to String by using UTF-8 encoding as shown in the code.

JSON decoding in Swift 4

But as you can see, the response JSON string we decoded is not really a thing that we can make use of doing anything besides displaying. We should be able to convert the data received as a model (class or struct) to have practical use. It is also known as JSON parsing.

This is where Codable, introduced in Swift 4, come in handy. We can make some structs or classes as models conforming this protocol. And these models can be encoded or decoded easily with data because by conforming to Codable, it automatically pairs with some convenient methods to use.

Let’s make a struct for our response as a model appending to our code.

struct Response: Codable { // or Decodable
let foo: String
}

Then we can decode the data received to this model like below.

if let url = URL(string: "https://api.myjson.com/bins/yfua8") {
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
do {
let res = try JSONDecoder().decode(Response.self, from: data)
print(res.foo)
} catch let error {
print(error)
}
}
}.resume()
}

And the console prints the following.

bar

This means that we successfully modelled the response data to res and print the value of the json key foo! And that's how we decode a JSON response using URLSession.

For more information on Encoding and Decoding, Apple has a good read on the custom types. You surely want to take a look.

This is the end of part one of the tutorial. In the next story I will illustrate how to play around Unsplash API using the above method as a more practical real world example.

The source code of this tutorial is available on Github.

Hope you find this useful :).

Have a nice day!

Software Engineer 🇭🇰