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

Calvin Wong
4 min readAug 4, 2018
“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.

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.

(EDIT 2023: previous mock API service myjson is no longer available and I replace it with jsonserve, you should find yourself alternative if jsonserve is not available in the future)

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 jsonserve 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.jsonserve.com/h89D3-. 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.jsonserve.com/h89D3-") {
// 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.jsonserve.com/h89D3-") {
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, 5 and onwards

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, comes in handy. We can make structs or classes as models conforming this protocol. And these models can be encoded or decoded easily with the 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.jsonserve.com/h89D3-") {
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 :)

Cheers!

--

--