我有一个关于新版Alamofire for Swift 2的问题

Alamofire.request(.POST, urlString, parameters: parameters as? [String : AnyObject])
        .responseJSON { (request, response, result) -> Void in
            let dico = result as? NSDictionary
            for (index, value) in dico! {
                print("index : \(index)     value : \(value)")
            }
    }

In this section I would like to cast the result in to a NSDictionary. But When I compile and put a breakpoint, the debugger says that dico is nil. If I use debugDescription to print result, it is not nil and contains what I expected How can I cast the Result variable?

推荐答案

公认的答案非常有效,但随着Alamofire 3.0.0的推出,有一些突破性的变化影响了该实现

  • Response
    All response serializers (with the exception of response) return a generic Response struct.

  • Response type
    The Result type has been redesigned to be a double generic type that does not store the NSData? in the .Failure case.

Also take in count that Alamofire treats any completed request to be successful, regardless of the content of the response. So you need to chain a .validate() before .responseJSON() to hit the .Failure case. Read more about it here.

更新代码:

let url = "http://api.myawesomeapp.com"
Alamofire.request(.GET, url).validate().responseJSON { response in
    switch response.result {
    case .Success(let data):
        let json = JSON(data)
        let name = json["name"].stringValue
        print(name)
    case .Failure(let error):
        print("Request failed with error: \(error)")
    }
}

For reference:

  • Xcode 7.3 (Swift 2.2)
  • Alamofire 3.3.1
  • SwiftyJSON 2.3.3

Json相关问答推荐

手动解开没有可编码的SON- Swift

如何获取brew list作为JSON输出

Python将Pandas转换为嵌套的JSON

使用PowerShell解析文件并获取特定行的值

PowerShell - 将 json 添加到文件内容

Android 如何判断小时时间是否在两个时间之间?

Groovy JsonBuilder 在for循环中添加数组元素

嵌套存储在字符串变量中的 JSON 对象

JOLT JSON 将值从一对多转换为一对一

如果值不存在,则将值插入 JSON 数组

字典和对象的模型创建问题

Java的JSON字符串整洁/格式化程序

JSON 到 JSON 转换器

Java循环遍历Json数组?

在浏览器中查看 JSON 文件

waitUntilAllTask​​sAreFinished 错误 Swift

你如何在 Arrays of Arrays 上 OPENJSON

C++:使用 nlohmann json 从文件中读取 json 对象

如何使用 SwiftyJSON 遍历 JSON?

通过url获取json数据并在python中使用(simplejson)