'Preview Crashed when I get data from api
I'm trying to fetch data from API according to a tutorial on YouTube and I does exactly as the video but the preview somehow crashed. But when I commented out the Api().getPosts , the preview is able to resume again. If that line of code is wrong how can I write it instead?
User Interface code:
import SwiftUI
struct ContentView: View {
@State var posts: [Post] = []
var body: some View {
VStack {
List(posts) { post in
Text(post.title)
}
.onAppear{
Api().getPosts { (posts) in
self.posts = posts
}
}
}//:VSTACK
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Api Service code:
import SwiftUI
struct Post: Codable, Identifiable {
var id = UUID()
var title: String
var body: String
}
class Api {
func getPosts(completion: @escaping([Post]) -> ()) {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else { return
print("Something occured!")
}
//CALL
URLSession.shared.dataTask(with: url) { data, response, error in
let posts = try! JSONDecoder().decode([Post].self, from: data!)
DispatchQueue.main.async {
completion(posts)
}
print(posts)
}//:URLSESSION
.resume()
}
}
Solution 1:[1]
use this code for your Post model:
struct Post: Codable, Identifiable {
// let id = UUID() // <-- or this
var id: Int // <-- here
var title: String
var body: String
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | workingdog support Ukraine |

