简体   繁体   English

如何在 swift 2 中获取 Alamofire.request().responseJSON 的结果值?

[英]How to get the result value of Alamofire.request().responseJSON in swift 2?

I have a question about the new version of Alamofire for Swift 2我有一个关于新版 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.在本节中,我想将结果转换为 NSDictionary。 But When I compile and put a breakpoint, the debugger says that dico is nil.但是当我编译并放置断点时,调试器说 dico 为零。 If I use debugDescription to print result, it is not nil and contains what I expected How can I cast the Result variable?如果我使用 debugDescription 打印结果,它不是 nil 并且包含我期望的内容 如何转换 Result 变量?

The accepted answer works great but with the introduction of Alamofire 3.0.0 there are some breaking changes that affects this implementation.接受的答案效果很好,但随着 Alamofire 3.0.0 的引入,有一些影响此实现的重大更改。
The migration guide has further explanations but i will highlight the ones related to the actual solution. 迁移指南有进一步的解释,但我会强调与实际解决方案相关的那些。

  • 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? Result 类型已重新设计为不存储 NSData 的双泛型类型? in the .Failure case..Failure情况下。

Also take in count that Alamofire treats any completed request to be successful, regardless of the content of the response.还要考虑到 Alamofire 将任何已完成的请求视为成功,而不管响应的内容如何。 So you need to chain a .validate() before .responseJSON() to hit the .Failure case.所以,你需要链.validate()之前.responseJSON().Failure情况。 Read more about it here .在此处阅读更多相关信息。

Updated code:更新代码:

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) Xcode 7.3 (Swift 2.2)
  • Alamofire 3.3.1阿拉莫火 3.3.1
  • SwiftyJSON 2.3.3 SwiftyJSON 2.3.3

If you don't mind using SwiftyJSON library, here's a working example in Xcode 7 Beta 5 + Alamofire 2.0.0-beta.1 + SwiftyJSON (xcode7 branch)如果您不介意使用SwiftyJSON库,这里有一个在 Xcode 7 Beta 5 + Alamofire 2.0.0-beta.1 + SwiftyJSON(xcode7 分支)中的工作示例

Alamofire.request(.GET, url, parameters: params, encoding: ParameterEncoding.URL).responseJSON { (_, _, result) in
    switch result {
        case .Success(let data):
            let json = JSON(data)
            let name = json["name"].string
        case .Failure(_, let error):
            print("Request failed with error: \(error)")
    }
}

Edit:编辑:

Updated SwiftyJSON git page更新了SwiftyJSON git 页面

You can now achieve most of the required behaviour out of the box without the need for SwiftyJSON for example.例如,您现在可以开箱即用地实现大部分所需的行为,而无需 SwiftyJSON。 My OAuthTokenResponse is a simple struct that is Codable.我的 OAuthTokenResponse 是一个可编码的简单结构。 The Alamofire library 5.2.2 lets you respond using the 'responseDecodable' Alamofire 库 5.2.2 允许您使用“responseDecodable”进行响应

If you have say a struct that looks like this:如果你有一个看起来像这样的结构:

struct OAuthTokenResponse : Codable
{
    var access_token:String?
    var token_type:String?
    var expires_in:Int?
    var scope:String?
}

And then in your network call (using Alamofire)然后在您的网络调用中(使用 Alamofire)

let request = AF.request(identityUrl, method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
    request
        .validate()
        .responseDecodable { (response:AFDataResponse<OAuthTokenResponse>) in
            
            switch response.result {
            case .success(let data):
                do {
                    let jwt = try decode(jwt: data.access_token!) // example
                    self.connected = true
                    print(jwt)
                } catch {
                    print(error.localizedDescription)
                    self.connected = false
                }
                
            case .failure(let error):
                    self.connected = false
                    print(error.localizedDescription)
            }
        
        }

In the above code, the success case automatically deserialises your JSON using the decodable protocol into your struct.在上面的代码中,成功案例使用可解码协议自动将您的 JSON 反序列化到您的结构中。 Any errors will result in the error case being hit instead.任何错误都将导致错误案例被命中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM