2017-07-03 99 views
0

我是iOS開發新手,使用swift語言。在我的應用程序中,我使用Alamofire 2網絡庫來調用rest api。現在我要動態填充uipickerview,我調用這個Web服務並獲得響應的JSON數組ios swift 2如何使用json數據填充uipickerview

[ 
{ 
    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). 

謝謝

+1

顯示你的企圖和錯誤請。 –

+0

解析JSON數據以將所有持續時間值存儲在數組中,並在您的UIPickerViewDelegate函數的實現中使用此數組 –

+0

是的@DSDharma它是一個重複的問題,正如我所說我是iOS開發新手並已經通過了你的建議例如,但無法獲取Json數組數據。 –

回答

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 
    } 
}