我正在尝试创建一个自定义PickerView,它从API调用到Web服务器获取数据。我遇到的问题是将解析后的数据保存到外部变量中,以便PickerView协议方法可以访问它。
// API Call / Parsing using Alamofire + Unbox
static func makeApiCall(completionHandler: @escaping (CustomDataStructure) -> ()) {
Alamofire.request(webserverUrl, method: .get).responseObject { (response: DataResponse<Experiment>) in
switch response.result {
case .success:
if var configParams = response.result.value {
let inputConfigs = removeExtrasParams(experiment: response.result.value!)
let modifiedViewModel = modifyViewModel(experiment: &configParams, inputConfigs: inputConfigs)
completionHandler(modifiedViewModel)
}
case .failure(_):
break
}
}
}
// Custom PickerClass
class CustomPickerView: UIPickerView {
fileprivate var customDS: CustomDataStructure?
override init() {
super.init()
dataSource = self
delegate = self
SomeClass.makeApiCall(completionHandler: { customds in
self.customDS = customds
})
}
...
}
extension CustomPickerView: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if let customds = customDS {
if let customDSValues = customds.inputs.first?.value {
return customDSValues[row]
}
}
return "apple"
}
}
extension CustomPickerView: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if let customds = customDS {
return customds.inputs.values.count
} else {
return 0
}
}
}
我遇到的问题是customDS每次都返回nil。
我在这里做错了什么?
答案 0 :(得分:2)
在makeApiCall
的完成块中,只需在主线程上重新加载pickerView's
组件,然后就可以开始了。
SomeClass.makeApiCall(completionHandler: { customds in
self.customDS = customds
DispatchQueue.main.async {
self.reloadComponent(0)
}
})