Show API data in XCode preview – Swift UI

You won’t be able to preview your layout in your XCode preview in Swift UI when you are receiving data from the server. So we are going to show you how you can preview the layout with the data from your API.

Video tutorial:

API to return JSON data

First, create an API that will return the JSON in a pretty format. We are going to create that API in PHP. You can find the sample database in the attachment below.

<?php

    $conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels");

    $result = mysqli_query($conn, "SELECT * FROM customers");

    $data = array();
    while ($row = mysqli_fetch_object($result))
    {
        array_push($data, $row);
    }

    header("Content-Type: application/json");

    echo json_encode($data, JSON_PRETTY_PRINT);

?>

It does the following things:

  1. Connect with the database.
  2. Fetch records from the customer’s table.
  3. Create a new empty array.
  4. Loop through all records from the database.
  5. Push in the array.
  6. Return the response as JSON pretty format.

If you run this file in your browser using XAMPP, WAMP, or MAMP, you will see all the data in JSON format. Copy all the content from the browser.

Create a JSON file in the XCode project

Now create a new file in your XCode project named “data.json”, you must select “Empty” while creating a new file in your XCode project. And paste the copied content into that file.

Create model class

Now in your View where you want to show the data, first create a model class that will hold the values you want to show in your List view.

// ResponseModel.swift

class ResponseModel: Codable, Identifiable {
    var customerName: String? = ""
    var country: String? = ""
}

Model class must implement Codable and Identifiable protocols.

Create an array of models

Inside your View class, create an array of these models and initialize it as an empty array.

@State var models: [ResponseModel] = []

List view

Now create a List view and show these 2 variables from the model class in the Text view.

VStack {
    List (models) { (model) in
        Text(model.customerName ?? "").bold()
        Text(model.country ?? "")
    }
}

This is the syntax to create a list view from an array. We are making the customer name to bold so we can differentiate between the customer name and country.

The layout could be different as per your need.

Read JSON file and Decode it into the model

Now we need to fill this “models” array with data from the JSON file we saved in our project. Following is the code that will read the JSON file from the XCode project and decode the JSON data into an array of models.

guard let url: URL = Bundle.main.url(forResource: "data", withExtension: "json") else {
    print("data.json not found")
    return
}

do {
    
    let data: Data = try Data(contentsOf: url)
    
    self.models = try JSONDecoder().decode([ResponseModel].self, from: data)
    
} catch {
    print(error.localizedDescription)
}

It does the following:

  1. Get the file from the bundle named “data.json”. The guard statement will throw an error if the file is not found. The bundle will return a URL object.
  2. Create a do-catch block that will throw an error if the data is not decodable to ResponseModel class.
  3. Convert the URL into a Data object.
  4. Decode the Data object into an array of ResponseModel class and assign it to the “models” array.

As “models” is a @State variable so it will automatically render the List view when the data is added to the model’s array.

Render List view

You can run the above inside your VStack’s onAppear function like below:

VStack {
    List (models) { (model) in
        Text(model.customerName ?? "").bold()
        Text(model.country ?? "")
    }
}.onAppear(perform: {

    // above code here

});

Conclusion

This is really helpful because when you are developing an app, you have to preview the layout you are designing in XCode, instead of re-running the app again and again to see the output.

You can do this with every API whose data you want to show in your Swift UI app. So that’s how you can show your API data in your XCode preview.

Learn how to create a search bar with history in Swift UI and SQLite.

Search bar Swift UI with history – SQLite

[wpdm_package id=’866′]

Leave a Reply

Your email address will not be published. Required fields are marked *