Post not yet marked as solved
Click to stop watching this thread.
You have stopped watching this post. Click to start watching again.
contentPostList.repliesup-voted.tooltip
Replied In
SwiftUI:how to show data from DB with picker
thank you for your answer,I have to show the data from my db,I get the data shown on List,when I get the data shown on pickerI get the the error:Thread 1: Fatal error: Index out of rangeit seems like i get nothing from users[]do you know how to modify it?I will really appreciate it if you can show me how to fill a foreach in picker to show all the data from users[]here is my code:ContentView.swift:import SwiftUI
struct SwiftUIView_Main: View {
var body: some View {
ContentViewpicker()
// ListView()
}
}
struct ContentViewpicker: View {
var body: some View {
let users = UserList().users
return Picker(selection: /*@START_MENU_TOKEN@*/.constant(1)/*@END_MENU_TOKEN@*/, label: /*@START_MENU_TOKEN@*/Text("Picker")/*@END_MENU_TOKEN@*/) {
Text(users[0].name).tag(1)
}
}
}
struct ListView: View {
@ObservedObject var store = UserList()
var body: some View {
List (store.users,id: \.id) { (user) in
UserRow(user: user)
}
}
}
struct UserRow: View {
var user: User
var body: some View {
HStack {
Text(String(user.id))
Text(user.name)
}
}
}
struct SwiftUIView_Main_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView_Main().previewLayout(.fixed(width: 1194, height: 834))
}
}UserList.swift:import Foundation
import Combine
class UserList: ObservableObject {
@Published var users: [User] = []
init() {
load()
}
func load() {
let url = URL(string: "http://localhost:3000/user")!
URLSession.shared.dataTask(with: url) { data, response, error in
DispatchQueue.main.async {
self.users = try! JSONDecoder().decode([User].self, from: data!)
}
}.resume()
}
}
//struct User: Decodable, Identifiable {
struct User: Decodable {
var id: Int
var name: String
}