我需要获取JSON数据并将其放在ViewController的pickerView中。 问题是我的应用在通过所有协议功能后调用了解析函数,因此没有加载任何pickerView。 首先获取数据然后将其加载到pickerView的最佳方法是什么?
谢谢!
override func viewDidLoad() {
super.viewDidLoad()
getCompanyList() // This is parse function which loads dictionary companiesListDict
private var companiesListDict: [String: String] = [:]
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.companiesListDict.keys.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return Array(self.companiesListDict.keys)[row]
}
UPD:
private func getCompanyList () {
if let url = URL(string: "https://api.iextrading.com/1.0/stock/market/list/infocus") {
let dataTask = URLSession.shared.dataTask(with: url) {data, response, error in
guard
error == nil,
(response as? HTTPURLResponse)?.statusCode == 200,
let data = data
else {
print("‼️ Network error")
return
}
self.parseCompanyList(data: data)
}
dataTask.resume()
}
}
private func parseCompanyList(data: Data) {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data)
guard
let companyList = jsonObject as? [Any]
else {print("‼️ Invalid JSON format"); return}
for company in companyList {
guard
let companyJson = company as? [String: Any],
let companyName = companyJson["companyName"] as? String,
let companyLabel = companyJson["symbol"] as? String
else {print("‼️ Invalid JSON format"); return}
self.companiesListDict[companyName] = companyLabel
}
DispatchQueue.main.async {
self.companyPickerView.reloadAllComponents()
self.companyPickerView.isHidden = false
}
}
catch {
print("JSON parsing error: " + error.localizedDescription)
}
}