how do I call a web api and show the results in a table view

Asked on 08/06/2024

1 search

To call a web API and show the results in a table view, you can follow these steps:

  1. Fetch Data from the Web API: Use URLSession to make an asynchronous request to the web API.
  2. Parse the JSON Response: Decode the JSON response into Swift model objects.
  3. Update the UI: Use SwiftUI to display the data in a table view.

Here’s a basic example to illustrate these steps:

Step 1: Fetch Data from the Web API

import Foundation

struct APIResponse: Codable {
    let results: [Result]
}

struct Result: Codable, Identifiable {
    let id: Int
    let name: String
}

func fetchData(completion: @escaping ([Result]) -> Void) {
    guard let url = URL(string: "https://api.example.com/data") else { return }
    
    URLSession.shared.dataTask(with: url) { data, response, error in
        if let data = data {
            do {
                let decodedResponse = try JSONDecoder().decode(APIResponse.self, from: data)
                DispatchQueue.main.async {
                    completion(decodedResponse.results)
                }
            } catch {
                print("Error decoding data: \(error)")
            }
        }
    }.resume()
}

Step 2: Parse the JSON Response

The fetchData function above decodes the JSON response into an array of Result objects.

Step 3: Update the UI

Use SwiftUI to display the data in a table view.

import SwiftUI

struct ContentView: View {
    @State private var results = [Result]()
    
    var body: some View {
        NavigationView {
            List(results) { result in
                Text(result.name)
            }
            .navigationTitle("Results")
            .onAppear {
                fetchData { fetchedResults in
                    self.results = fetchedResults
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Example from WWDC Sessions

For more detailed examples, you can refer to the following sessions from WWDC:

These sessions provide practical examples and best practices for fetching data from web APIs and displaying it in your app using SwiftUI.