0

I am downloading a JSON Array from a remote server:

var colores = [Colores]()


func downloadJSONColores(completed: @escaping () -> ()) {
         let url = URL(string: "https://../colores.php")


         URLSession.shared.dataTask(with: url!) { (data,response,error) in

            print(data as Any)
            print(response as Any)

         if error == nil {
             do {
                 self.colores = try JSONDecoder().decode([Colores].self, from: data!)

                 DispatchQueue.main.async {
                     completed()
                 }

             }catch{

             }

         }
         }.resume()


     }

I have a struct class for Colores:

struct Colores:Decodable {

    let id: Int
    let nombre: String
    let icono: String
    let modelo: Int
    let caracterista: Int

}

What I need is to populate a PickerView with the decoded JSON objects, showing the field nombre as title and storing the field id from the pickerview selected item.

I am calling the downloadJSONColores method in viewDidLoad as follows:

downloadJSONColores {
            coloresPV.reloadData()
                     }

where coloresPV is my pickerView, but obviously this way of doing this only works for collectionViews, not for pickerViews. Which would be the best way to populate the pickerView while executing downloadJSONColores?

2 Answers 2

1

I have solved my problem decoding the JSON Array directly at viewDidLoad method as follows:

let url = URL(string: "https://..")!
let dataTask = URLSession.shared.dataTask(with: url) { data, _, error in
    if let error = error { print(error); return }
    do {
        let result = try JSONDecoder().decode([Colores].self, from: data!)
        print(result)
        self.colores = result.map{$0.self}
        DispatchQueue.main.async {
          self.coloresPV.reloadAllComponents()
        }
    } catch { print(error) }
}
dataTask.resume()
Sign up to request clarification or add additional context in comments.

Comments

0

Take a look at the UIPickerViewDataSource and UIPickerViewDelegate protocols.

If I understand your question correctly, you'll need to keep a variable colors: [Colores] in your ViewController.

Then:

  • Return colors.count in your implementation of the func numberOfComponents(in: UIPickerView) -> Int function of UIPickerViewDataSource,

  • Return the correct title in your implementation in the method pickerView(UIPickerView, titleForRow: Int, forComponent: Int) -> String? function of UIPickerViewDelegate

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.