Get data from API and show in list – Swift UI, PHP

We will create a simple iOS app in Swift UI that will call an API request, developed in PHP, to the HTTP server. The API will return an array of records in JSON format, which we will decode in Swift class objects as an array. Then we will display that list in a list view.

If you prefer a video tutorial:

Our API will be in PHP and we will call it from our Swift UI app. So, create a file in your htdocs (for XAMPP), or www (for MAMP or WAMP) folder and paste the following code in it. We have created a folder named “test” and inside it, the file name is “swiftui-get-data-from-api.php”:

<?php

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

    // get data from database
    $result = mysqli_query($conn, "SELECT * FROM customers");

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

    // send as response
    echo json_encode($data);

?>

For that, you need to create a database named “classicmodels” in your phpMyAdmin and import the SQL file attached below. You need to create and login into your account in order to download that file. You can see the output from the link:

http://localhost/test/swiftui-get-data-from-api.php

This might be changed and it depends on the path of your file. You will see a lot of data, for example, we want to show only customerName and country in our Swift UI app. So you need to create a model file in your project using XCode and paste the following code into it:

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

Now in your View file where you want to show the list, you can paste the following code:

@State var models: [ResponseModel] = []
    
var body: some View {
    // Create VStack
    VStack {
        // now show in list
        // to show in list, model class must be identifiable
        
        List (self.models) { (model) in
            HStack {
                // they are optional
                Text(model.customerName ?? "").bold()
                Text(model.country ?? "")
            }
        }
        
    }.onAppear(perform: {
        // send request to server
        
        guard let url: URL = URL(string: "http://localhost:8888/test/swiftui-get-data-from-api.php") else {
            print("invalid URL")
            return
        }
        
        var urlRequest: URLRequest = URLRequest(url: url)
        urlRequest.httpMethod = "GET"
        URLSession.shared.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
            // check if response is okay
            
            guard let data = data else {
                print("invalid response")
                return
            }
            
            // convert JSON response into class model as an array
            do {
                self.models = try JSONDecoder().decode([ResponseModel].self, from: data)
            } catch {
                print(error.localizedDescription)
            }
            
        }).resume()
    })
}

All the code is self-explanatory and comments are also added to explain difficult lines. But if you still face any issues in following this tutorial, please let us know.

[wpdm_package id=’847′]

5 Replies to “Get data from API and show in list – Swift UI, PHP”

  1. Hi,

    I use the mysql database and the exact copy of the source.
    Also the php file is exact the same and is available on my hosted server.
    But this is the error I get.

    2021-09-10 19:59:59.312846+0200 Get data from API and show in List[3288:85052] [] nw_protocol_get_quic_image_block_invoke dlopen libquic failed
    The data couldn’t be read because it isn’t in the correct format.

    Hope you can help me out?

    Ton

  2. I found the reason why I didn’t get the right data. It was the PHP version and Mysqli Functions.
    The only warning that I get now is nw_protocol_get_quic_image_block_invoke dlopen libquic failed.
    But that could be a bug from Xcode Version 12.5.1 (12E507).

    Thanks for your help Adnan.

Comments are closed.