我对新版 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)")
}
}
在本节中,我想将结果转换为 NSDictionary。但是当我编译并设置断点时,调试器说 dico 是 nil。如果我使用 debugDescription 打印结果,它不是 nil 并且包含我所期望的 如何转换 Result 变量?
最佳答案
已接受的答案效果很好,但随着 Alamofire 3.0.0 的引入,一些重大更改会影响此实现。
migration guide有进一步的解释,但我会强调与实际解决方案相关的那些。
Response
所有响应序列化程序(除了响应)都返回一个通用的响应结构。Response type
Result 类型已被重新设计为不存储 NSData 的双重泛型类型?在.Failure
的情况下。
还要考虑到 Alamofire 将任何已完成的请求视为成功,无论响应的内容如何。因此,您需要在 .responseJSON()
之前链接 .validate()
以达到 .Failure
的情况。
阅读更多信息 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)")
}
}
供引用:
- Xcode 7.3 (Swift 2.2)
- Alamofire 3.3.1
- SwiftyJSON 2.3.3
关于ios - 如何在 swift 2 中获取 Alamofire.request().responseJSON 的结果值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32018741/