swiftui:I can show data from db in list, but it shown nothing in picker, how can I fix it
here is my code:
ContentView.swift:
import SwiftUI
struct ContentView: View {
@ObservedObject var model = PostListViewModel()
@State private var selectedStrength = 0
var body: some View {
// List(model.posts) { post in
// Text(String(post.name))
// }
Picker(selection: $selectedStrength, label: Text("picker")) {
ForEach(model.posts) { post in
Text(post.name)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
PostListViewModel.swift
import Foundation
import SwiftUI
import Combine
final class PostListViewModel: ObservableObject {
init() {
fetchPosts()
}
@Published var posts = [Post]()
private func fetchPosts() {
Webservice().getAllPosts {
self.posts = $0
}
}
}
Post.swift
import Foundation
import SwiftUI
struct Post: Codable,Hashable,Identifiable{
let id: Int
let name: String
}
Webservice.swift
import Foundation
class Webservice{
func getAllPosts(completion: @escaping ([Post]) -> ()){
guard let url = URL(string:
"http://localhost:3000/user")
else{
fatalError("URL is not correct")
}
URLSession.shared.dataTask(with: url){ data, _, _ in
let posts = try!
JSONDecoder().decode([Post].self, from: data!)
DispatchQueue.main.async {
completion(posts)
}
}.resume()
}
}