Reputation: 37
I have a picker in swiftui, which i need to fill from a json that i'm currently hosting on my mac.
As I'm running the code, the picker displayed stays empty but the data is available (if I click on a button below which prints it).
Here is my code:
Picker (ContentView.swift):
@State var nwm = NetworkManager()
...
Picker("Wähle deine Schule", selection: $selectedSchool) {
ForEach(0 ..< nwm.schoolList.results.count) {
Text(self.nwm.schoolList.results[$0].name).tag($0)
}
}.labelsHidden()
NetworkManager.swift:
class NetworkManager : ObservableObject {
var didChange = PassthroughSubject<NetworkManager, Never>()
var schoolList = SchoolList(results: []) {
didSet {
didChange.send(self)
}
}
init() {
guard let url = URL(string: "http://jonasmacbookpro.local:8083/IOSApp/getDKSchools") else { return }
URLSession.shared.dataTask(with: url) {
(data, _, _) in
let schoolList = try! JSONDecoder().decode(SchoolList.self, from: data!)
DispatchQueue.main.async {
self.schoolList = schoolList
}
}.resume()
}
}
School.swift
struct School : Identifiable, Decodable {
let id = UUID()
var name : String
var ort : String
var link : String
}
struct SchoolList: Decodable {
var results: [School]
}
Does anyone know, why it isn't working?
Upvotes: 1
Views: 420
Reputation: 4719
To make the picker refresh is to add a unique id. You can add .id(UUID())
to your Picker and it should be work fine
Upvotes: 0
Reputation: 257711
Instead of
@State var nwm = NetworkManager()
Use
@ObservedObject var nwm = NetworkManager()
and instead of
var didChange = PassthroughSubject<NetworkManager, Never>() var schoolList = SchoolList(results: []) { didSet { didChange.send(self) } }
use
@Published var schoolList = SchoolList(results: [])
Upvotes: 1