我是iOS开发新手,使用的是swift语言。在我的应用程序中,我使用Alamofire 2网络库来调用rest api。现在我想动态填充uipickerview,我正在调用这个Web服务并将响应作为json数组
[
{
duration = "2017 - 2018";
year = 2017;
}
{
duration = "2016 - 2017";
year = 2016;
}
{
duration = "2015 - 2016";
year = 2015;
}
]
现在我想用“持续时间”数据填充uipickerview,我已经完成了各种示例,但无法理解如何执行此操作。任何帮助表示赞赏。
Swift代码:
func getYear()
{
url = baseUrl + "/foo/bar"
Alamofire.request(.GET, url , parameters: ["foo": foo,"bar":bar])
.responseJSON(){
(_,_,result)
in
print("get year list result ",result)
switch result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
let jsonData = JSON as! NSDictionary
let duration = jsonData.objectForKey("duration")
print("duration ",duration)
case .Failure(let data, let error):
print("Request failed with error: \(error)")
if let data = data {
print("Response data: \(NSString(data: data,
encoding: NSUTF8StringEncoding)!)")
}
}
}
}
控制台消息
get year list result SUCCESS
Success with JSON:
(
{
duration = "2017 - 2018";
year = 2017;
}
)
Getting this error
Could not cast value of type '__NSCFArray' (0x394c92d0) to 'NSDictionary' (0x394c93c0).
谢谢
答案 0 :(得分:1)
将数据解析为数组: -
yourModel : NSObject {
var duration: String?
var year : String?
}
假设:yourArray = [yourModel]()
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return yourArray.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if yourArray.count > 0 {
return yourArray[row].duration
}
}