如何在Swift 2中获取Alamofire.request().responseJSON的结果值? [英] How to get the result value of Alamofire.request().responseJSON in swift 2?

查看:93
本文介绍了如何在Swift 2中获取Alamofire.request().responseJSON的结果值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Swift 2的Alamofire新版本有疑问

I have a question about the new version of 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为零.如果我使用debugDescription打印结果,则它不是nil,并且包含我期望的结果 如何转换Result变量?

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的引入,有一些重大更改会影响此实现.
迁移指南进行了进一步的解释,但我将重点介绍其中的解释.与实际解决方案有关.

The accepted answer works great but with the introduction of Alamofire 3.0.0 there are some breaking changes that affects this implementation.
The migration guide has further explanations but i will highlight the ones related to the actual solution.

  • 响应
    所有响应序列化器(响应除外)都返回通用的响应结构.

响应类型
结果类型已重新设计为不存储NSData的双泛型类型?在.Failure情况下.

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

还要考虑到Alamofire将任何已完成的请求视为成功,无论响应的内容如何.因此,您需要在.responseJSON()之前链接一个.validate()才能打出.Failure大小写. 在此处了解更多信息.

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

供参考:

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

这篇关于如何在Swift 2中获取Alamofire.request().responseJSON的结果值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆