使用Alamofire在Swift中下载和解析json

时间:2015-01-30 03:22:14

标签: ios json swift alamofire

对不起,我对此很陌生,而且他们可能是一个明显的东西,但是我收到了以下错误消息:

"致命错误:在打开可选值时意外发现nil。"

   var jsonReceived = Alamofire.request(.GET, getJsonURL).responseJSON {
        (request, response, jsonData, error) in
        if jsonData == nil {
            println(error)
        } else {
            println(jsonData)
            var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
            println(jsonResult)
        }
    }

1 个答案:

答案 0 :(得分:4)

为简单起见,我已将Alamofire.request代码放入viewDidLoad()。你可以把它放在任何你想要的地方。

override func viewDidLoad() {
    Alamofire.request(.GET, getJsonURL).responseJSON {
            (request, response, jsonData, error) in
            if error != nil {
                println(error)
            } else if let json = jsonData as? [String:AnyObject] {
                println(json)

                // call a function with the new data. 
                self.processNewData(json)

                // or you could just use the json object here
                if let str = json["foo"] as? String {
                    self.myButton.setTitle(str, forState: .Normal)
                }
            } else {
                println("Failed to cast JSON to [String:AnyObject]")
            }
        }
}

func processNewData(json: [String:AnyObject]){
    // do whatever you want here with the parsed JSON
    if let str = json["bar"] as? String {
        myLabel.text = str
    }
}