Fetch Data From JSON File And Display It On The Screen - Swift

In this article, we will be creating a simple application that will display data fetched from the JSON file. This app will be demonstrating how to fetch data from JSON files stored in a remote URL and also from the JSON file stored in the App Bundle.

For creating this project, you'll need,

  • macOS
  • Xcode installed on your Mac

So let’s get started.

Step 1

Open Xcode and create a new project. Select iOS -> Single View App. Name your project and choose the language as Swift. Select the desired location to save your project.

Step 2

Let’s design the UI first. Open Main.storyboard. Let’s embed our View Controller in the Navigation Controller. The Navigation Controller helps us to navigate from one screen to another. To embed the View Controller into Navigation Controller, select Embed In -> Navigation Controller.

Fetch Data From JSON File And Display It On The Screen

Step 3

Next, design the UI as shown in the below image. Connect the outlets of the tableview and segment control on the View Controller. Also, create an Action type outlet for Segment Control.

Fetch Data From JSON File And Display It On The Screen

Step 4

Add delegate and data source for tableview. For this, click on the tableview and clicking the Ctrl button drag it towards the View Controller icon at the top. On releasing the mouse, a black box must appear in a similar manner. Click on ‘delegate’ and ‘dataSource’.

Fetch Data From JSON File And Display It On The Screen

Step 5

Also, name the identifier of the table view cell.

Fetch Data From JSON File And Display It On The Screen

Step 6

Change the titles of the segments by selecting the segment of the Segment Control.

Fetch Data From JSON File And Display It On The Screen

Step 7

Here, we complete the UI Part. Now let’s go to the coding part. Go to File -> New-> File -> Swift. Let’s name the file as Data.swift.

Step 8

Add the following code to this file.

enum Type : Int{
    case url = 0
    case appBundle = 1
}

Step 9

As you can see, in the above code we have created an Enum which consists of 2 cases. This enum will help the app to identify the segment that the user has chosen.

Step 10

Now, paste the following code into the same file.

struct CountryCodes: Codable {
    var name: String
    var code: String
}
struct States: Codable {
    var state: String
    var year: Int
}

Step 11

In the above code, we have created Structs for the respective JSON files that we will be using in our project.

Step 12

Now, create another new Swift file and name it as DataLoader.

Step 13

Copy and paste the following code in DataLoader.swift file.

import Foundation
public class DataLoader {
    var countryCodes = [CountryCodes]()
    var states = [States]()
    init() {
        load()
    }
    func load() {
        //url where the JSON file is located
        let url = URL(string: "https://gist.githubusercontent.com/krsanu555/6a89cb1aad073a71e869eb19c0c09a5e/raw/bbecb7679c6da7191c86e9d677005496ab6350b7/India-States-And-Its-Formation.json") !
            //to fetch data stored in the app bundle file
            let fileLocation = Bundle.main.url(forResource: "country-codes", withExtension: "json") !do {
                    let dataUrl =
                        try Data(contentsOf: url)
                    let dataFromAppBundle =
                        try Data(contentsOf: fileLocation)
                    let jsonDecoder = JSONDecoder()
                    let urlDataFromJson =
                        try jsonDecoder.decode([States].self, from: dataUrl)
                    let appBundleDataFromJson =
                        try jsonDecoder.decode([CountryCodes].self, from: dataFromAppBundle)
                    self.states = urlDataFromJson
                    self.countryCodes = appBundleDataFromJson
                } catch {
                    print(error)
                }
    }
}

Step 14

Swift file consists of code to fetch data from a JSON file located in a remote URL as well as from the JSON file that we have stored in our App Bundle.

Step 15

For fetching data from a remote URL, you need to add the link where the JSON file is located. In the above code, you can see a link with a file named ‘India-States-And-Its-Formation.json’. That’s the remote URL that we have used in our code.

Step 16

For fetching data from App Bundle, you need to add the JSON file in the project. Here, I have used the ‘country-codes.json’ file.

Step 17

The JSON data in my ‘country-codes’ file is as shown below,

[{
    "name": "Australia",
    "code": "AU/AUS"
}, {
    "name": "France",
    "code": "FR/FRA"
}, {
    "name": "India",
    "code": "IN/IND"
}, {
    "name": "Mexico",
    "code": "MX/MEX"
}, {
    "name": "New Zealand",
    "code": "NZ/NZL"
}, {
    "name": "Singapore",
    "code": "SG/SGP"
}, {
    "name": "Thailand",
    "code": "TH/THA"
}, {
    "name": "United States",
    "code": "US/USA"
}]

Step 18

Add the JSON file into the project by right-clicking on the project folder and choose ‘Add Files to the Project’. Select the JSON file and add it to your project.

Step 19

The JSON file must be visible in the project.

Fetch Data From JSON File And Display It On The Screen

Step 20

Now, go to ViewController.swift file and add the below code,

import UIKit
class ViewController: UIViewController {
    @IBOutlet weak
    var tableView: UITableView!@IBOutlet weak
    var segmentControl: UISegmentedControl!
        var type = Type.appBundle
    let bundleData = DataLoader().countryCodes
    let urlData = DataLoader().states
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    @IBAction func sgmtcntrlChanged(_ sender: Any) {
        if segmentControl.selectedSegmentIndex == Type.url.rawValue {
            let data = urlData
            print(data)
        } else {
            let data = bundleData
            print(data)
        }
        tableView.reloadData()
    }
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) - > Int {
        if segmentControl.selectedSegmentIndex == Type.url.rawValue {
            return urlData.count
        } else {
            return bundleData.count
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) - > UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "data",
            for: indexPath)
        if segmentControl.selectedSegmentIndex == Type.url.rawValue {
            cell.textLabel?.text = urlData[indexPath.row].state
            cell.detailTextLabel?.text = String(urlData[indexPath.row].year)
        } else {
            cell.textLabel?.text = bundleData[indexPath.row].name
            cell.detailTextLabel?.text = bundleData[indexPath.row].code
        }
        return cell
    }
}

Step 21

We are done! Run your project and if everything goes well then you must see the below output. You will be able to see the data of JSON files from both URLs as well as App Bundle on the tableview.

Fetch Data From JSON File And Display It On The Screen

Fetch Data From JSON File And Display It On The Screen

Summary

So in this article, we learned how to fetch data from JSON File and display it on the screen.


Similar Articles