【问题标题】:ios swift 2 how to populate uipickerview with json data [duplicate]ios swift 2如何用json数据填充uipickerview [重复]
【发布时间】:2017-07-03 09:10:59
【问题描述】:

我是 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).

谢谢

【问题讨论】:

  • 请显示您的尝试和错误。
  • 解析 JSON 数据以将所有持续时间值存储在一个数组中,并在 UIPickerViewDelegate 函数的实现中使用该数组
  • 是的@DSDharma,这是一个重复的问题,正如我所说,我是 iOS 开发的新手,并且通过了您建议的示例,但无法获取 Json Array 数据。

标签: ios json swift alamofire


【解决方案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
    }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多