I get data from a server and I have the following JSON:
(
{
id = 1;
status = 1;
title = "jimmy";
},
{
id = 2;
status = 1;
title = "arnold";
},
{
id = 3;
status = 1;
title = "mike";
}
)
I want to load the title of this JSON in a picker view and when I select one of them, the id of the selected row is set in the myID variable. I wrote the below code but the picker view doesn't show anything:
var dictionary = [[String : AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
pickerDep.delegate = self
pickerDep.dataSource = self
var Token=FuncClass.ReadData(_file: "fileToken.txt")
let url=Property._URL+"getTicketDepartment"
let parameters = [
"token": Token
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).responseJSON { response in
if let data = response.data {
let json = String(data: data, encoding: String.Encoding.nonLossyASCII)
let result=response.result
self.dictionary = (result.value as? [Dictionary<String,AnyObject>])!
}
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dictionary.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return dictionary[row]["title"] as! String
}
What should I do?
You need to reload the picker view after the data is loaded from Alamofire:
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).responseJSON { response in
if let data = response.data {
let json = String(data: data, encoding: String.Encoding.nonLossyASCII)
let result=response.result
if let array = result.value as? [Dictionary<String,AnyObject>] {
self.dictionary = array
pickerDep.reloadAllComponents()
}
}
}
BTW - why is your property named dictionary
when it contains an array of data?