Fetching and Displaying API Data in SwiftUI: A Step-by-Step Guide

Fetch and Display API Data in SwiftUI: Display User Details from JSONPlaceholder

Fetching data from an API and displaying it in your SwiftUI app is a common task that’s crucial for building dynamic, data-driven applications. Let’s walk through how to fetch user data from the JSONPlaceholder API and display it on the screen using SwiftUI.

1. Setting Up the Data Model

First, create a data model that matches the structure of the API response. For the https://jsonplaceholder.typicode.com/users API, the model might look like this:

struct User: Identifiable, Decodable {
    let id: Int
    let name: String
    let username: String
    let email: String
    let phone: String
}        

This User struct conforms to both Identifiable and Decodable, making it easy to decode JSON and use it in a SwiftUI list.

2. Fetching Data from the API

Next, create a view model that handles the API request and stores the fetched data:

class UserViewModel: ObservableObject {
    @Published var users: [User] = []

    func fetchUsers() {
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { return }

        URLSession.shared.dataTask(with: url) { data, response, error in
            if let data = data {
                if let decodedResponse = try? JSONDecoder().decode([User].self, from: data) {
                    DispatchQueue.main.async {
                        self.users = decodedResponse
                    }
                }
            }
        }.resume()
    }
}        

This UserViewModel uses URLSession to fetch the user data from the API, decodes it, and updates the users array.

3. Displaying the Data in a SwiftUI View

Finally, use the fetched data to display a list of users in your SwiftUI view:

struct ContentView: View {
    @StateObject private var viewModel = UserViewModel()

    var body: some View {
        NavigationView {
            List(viewModel.users) { user in
                VStack(alignment: .leading) {
                    Text(user.name)
                        .font(.headline)
                    Text(user.username)
                        .font(.subheadline)
                    Text(user.email)
                        .font(.subheadline)
                    Text(user.phone)
                        .font(.subheadline)
                }
                .padding(.vertical, 5)
            }
            .navigationTitle("Users")
            .onAppear {
                viewModel.fetchUsers()
            }
        }
    }
}        

In this ContentView, the List view is used to display each user's details. The onAppear modifier triggers the fetchUsers method when the view appears, ensuring that data is loaded when needed.

Fetching and displaying data from an API is a fundamental skill in iOS development. SwiftUI makes it easy to build responsive and dynamic UIs that react to data changes. By structuring your app with models, view models, and views, you can create clean, maintainable code that scales well.

To view or add a comment, sign in

More articles by Dion James Smith

Explore content categories