Display API Data on List Using SwiftUI

To display API data in a list using SwiftUI, you’ll need to fetch the data from the API and then use SwiftUI’s `List` view to render it. Below is a basic example demonstrating how to achieve this:

import SwiftUI

// Define a model to represent your API data
struct Post: Codable {
let id: Int
let title: String
let body: String
}

// Define a view model to fetch data from the API
class PostsViewModel: ObservableObject {
@Published var posts: [Post] = [] 
init() {

// Fetch data from the API
fetchData()
} 
func fetchData() {

// Perform network request to fetch data from the API
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, error == nil else {
print("Failed to fetch data: \(error?.localizedDescription ?? "Unknown error")")
return
}
do {

// Decode the JSON data into an array of Post objects
let posts = try JSONDecoder().decode([Post].self, from: data)
DispatchQueue.main.async {

// Update the @Published property to trigger view updates
self.posts = posts
}
} catch {
print("Failed to decode data: \(error.localizedDescription)")
}
}.resume()
}
}

// Define a SwiftUI view to display the list of posts
struct ContentView: View {
@ObservedObject var viewModel = PostsViewModel()

var body: some View {
NavigationView {
List(viewModel.posts, id: \.id) { post in
VStack(alignment: .leading) {
Text(post.title)
.font(.headline)
Text(post.body)
.font(.subheadline)
.foregroundColor(.gray)
}
}
.navigationTitle("Posts")
}
}
}

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

In this example:

1. We define a `Post` struct to represent the data fetched from the API.
2. We define a `PostsViewModel` class that conforms to `ObservableObject` to fetch data from the API and publish it to the view.
3. In the `fetchData` method of the view model, we use `URLSession` to perform a network request to fetch data from the API, decode the JSON response into an array of `Post` objects, and update the `posts` property.
4. We define a `ContentView` SwiftUI view that displays a `List` of posts fetched from the API using the `PostsViewModel`.
5. The `ContentView` uses `Navigation` to display a navigation bar with the title “Posts”.
6. Finally, we preview the `ContentView` using `ContentView_Previews`.