April 22, 2020

Get JSON array from the server and parse it in your ios application.

By Mohit Agrawal

Learn how to parse a JSON array with the model class.

API call function

In this small tutorial, I will show you how to get JSON array and parse the respective data in your iOS app. Let’s get started. For the demo, I will be using this link for the JSON array.

“https://jsonplaceholder.typicode.com/posts”

This JSON contains the array of post data. So let’s create our model PostModel.swift as shown in the below code. If you are using different JSON responses and its object then make your own model structure.

struct Post: Decodable {
    let userId: Int
    let id: Int
    let title: String
    let body: String
}

Now I have made it very easy for you guys to display the JSON data. Just use the function fetchJsonData with your model class.

import UIKit
import Foundation

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        
        fetchJsonData() { (posts, error) in
            if let err = error {
                print(err)
                return
            }
            
            posts?.forEach() { (post) in
                print(post.title + "\n")
            }
        }
    }
    
    func fetchJsonData(completion: @escaping ([Post]?, Error?) -> ()) {
        let urlString = "https://jsonplaceholder.typicode.com/posts"
        guard let url = URL(string: urlString) else { return }
        URLSession.shared.dataTask(with: url) { (data, resp, error) in
            
            if let err = error {
                completion(nil, err)
                return
            }
            
            //successfull
            do {
                let posts = try JSONDecoder().decode([Post].self, from: data!)
                completion(posts, nil)
            } catch {
                completion(nil, error)
            }
            }.resume()
    }
    
}

I recommend you to check this related post Asynchronously display data from API call in iOS.

How to display JSON array in iOS swift?

Displaying JSON or printing is a very easy job. First, make the URL. Call the URL using URLSession. Now in the completion handler of URLSession, you will be getting a response. This response you can print a string. But to map it to your model class you need to do the decoding.

Is it tough to learn API calls in iOS swift?

No, It is an easy but little tricky. I am telling this because you need to learn asynchronous and synchronous task concepts to make a smooth application.