Hi,
I'm getting data from an api and reading it to a model that contains (among other things) an id and a name.
I can get the picker to populate using a ForEach loop so that when I click, I get the list showing the name, I just can't seem to return the id and then show the name in the picker as the selected item.
I feel like I'm missing something simple, but just can't seem to spot it.
Any help would be gratefully received.
Thanks
I'm getting data from an api and reading it to a model that contains (among other things) an id and a name.
I can get the picker to populate using a ForEach loop so that when I click, I get the list showing the name, I just can't seem to return the id and then show the name in the picker as the selected item.
I feel like I'm missing something simple, but just can't seem to spot it.
Code Block Picker("Pick an item", selection: $ID) { ForEach(mydata, id: \.ID) { mymodel in Text(mymodel.Name) } }.onAppear(perform: loadData) Text("Selected: \(ID)")
Any help would be gratefully received.
Thanks
Far from complete. Simply saying a complete code is a self contained code which can be built and run without any guesses.This is my complete code:
If you could guess what is needed for readers properly, more readers would take time to solve your issue and you would get better responses sooner.Sorry, didn't think that you'd need that as well
You declare ID of MyModel as String, so the type of selection needs to match to it:
Code Block struct MyView: View { @State var mydata = [MyModel]() @State private var ID: String = "" //<- var body: some View { NavigationView { Form { Section { Picker("Pick an item", selection: $ID) { ForEach(mydata, id: \.ID) { mymodel in Text(mymodel.Name) //`name` or `Name` } }.onAppear(perform: loadData) Text("Selected: \(ID)") } } } } //... }
Assuming your loadData() works properly. But generally, you should better not dispose error info silently:
Code Block func loadData() { guard let url = URL(string: "https://mysite.co.uk/api/getmydatalist") else { print("Invalid URL") return } let request = URLRequest(url: url) URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print(error) return } guard let data = data else { print("data is nil") return } do { let response = try JSONDecoder().decode([MyModel].self, from: data) DispatchQueue.main.async { self.mydata = response } } catch { print(error) } }.resume() }