DEV Community

Roby Cigar
Roby Cigar

Posted on

How to Fetch Data in SwiftUI

Fetching data from an API in SwiftUI can be done using the URLSession class provided by the Swift standard library. Here's an example of how to fetch data from an API and display it in a SwiftUI view:

import SwiftUI

struct ContentView: View {
    @State private var data: [Post] = []

    var body: some View {
        List(data, id: \.id) { post in
            VStack(alignment: .leading) {
                Text(post.title)
                Text(post.body)
                    .font(.subheadline)
                    .foregroundColor(.secondary)
            }
        }
        .onAppear {
            fetchData()
        }
    }

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

        URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data else { return }
            do {
                let posts = try JSONDecoder().decode([Post].self, from: data)
                DispatchQueue.main.async {
                    self.data = posts
                }
            } catch {
                print(error.localizedDescription)
            }
        }.resume()
    }
}

struct Post: Codable {
    let id: Int
    let title: String
    let body: String
}
Enter fullscreen mode Exit fullscreen mode

In this example, a List is used to display the data fetched from the API. The @State property wrapper is used to store the fetched data as a property of the view. The onAppear modifier is used to trigger the fetchData() method when the view appears.

The fetchData() method uses URLSession.shared.dataTask(with:completionHandler:) to fetch data from the API. The fetched data is then decoded using JSONDecoder() and stored in the data property using the DispatchQueue.main.async method to ensure that the UI is updated on the main thread.

Note that in this example, the Post struct conforms to the Codable protocol, which allows it to be decoded from JSON data using the JSONDecoder() class provided by the Swift standard library. If the API returns data in a different format, you may need to use a different decoding method or update the Post struct to match the data format.

Top comments (0)