April 23, 2020

Asynchronously display data from API call in iOS

By Mohit Agrawal

Learn how to make API call in iOS. Display the returned data asynchronously in iOS swift

ios async

In this tutorial we will be using a dummy API to make API call in iOS ie.

https://jsonplaceholder.typicode.com/todos/1

And the response will be coming in JSON as shown below format:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

Let’s start some coding now. First we will be creating the model class based on the above JSON array.

// MARK: - Todo
struct Todo: Codable {
    let userID, id: Int
    let title: String
    let completed: Bool

    enum CodingKeys: String, CodingKey {
        case userID = "userId"
        case id, title, completed
    }
}

Above structure is the our required model class.

Our aim is to get the “title” from JSON response and set the value to UILabel. We got everything ready, just we need to make an API call using URLSession.shared.dataTask() . Below is the code :

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var titleLable: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        fetchData()
    }
    
    func fetchData() {
        let urlString = "https://jsonplaceholder.typicode.com/todos/1"
        guard let url = URL(string: urlString) else {return}
        URLSession.shared.dataTask(with: url) { (data, res, error) in
    
            do {
                let todoDetails = try JSONDecoder().decode(Todo.self, from: data!)
                DispatchQueue.main.async {
                    self.titleLable.text = todoDetails.title
                }
            } catch {}
        }.resume()
    }
}

Bingo!!! You got the source code. Now the function fetchData() will be called in view did load and it will be updating the titleLable‘s text. We have covered everything but where is the asynchronous concept?

Here it is If you look inside the fetchData() function I am using the DispatchQueue.main.async{}. Basically it will be updating the UILable text asynchronously as soon as we get the data from API. If you don’t use the async method then you will be getting this serious warning and your app will crash.

GitHub source code link https://github.com/warmodroid/Asyn-API-call-iOS-in-swift

Now let’s summarise what we have done till now in the few and simple steps below.

Time Needed : 5 minutes

How to make API call in iOS swift?

  1. Required URL.

    Make the required URL. Here in our example API URL will “https://jsonplaceholder.typicode.com/todos/1”. This API returns a JSON array.JSON response

  2. Create the model class.

    Now we need to create a model class so that we can map the JSON response to it.todo model class

  3. Call the URL.

    Now it's the time to call the URL using URLSession.shared.dataTask(). It has the completion handler which returns the response, data, and error.call url

  4. Map the JSON to our model class.

    Since we already got the data in the previous step, so now we just need to map the JSON array to our model class and this can be done using JSONDecoder.call url

Tools
  • xcode

How to get an API response in iOS swift?

Make the required URL.
Now we need to create a model class so that we can map the JSON response to it.
It’s the time to call the URL using URLSession.shared.dataTask(). It has the completion handler which returns the response, data, and error.
Since we already got the data in the previous step, so now we just need to map the JSON array to our model class and this can be done using JSONDecoder.

What is API in Swift iOS?

API stands for Application Programming Interface. It is used to transfer the data from the mobile device to the server and vice versa.