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

后端 未结 3 1796
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 14:28

I have a question about the new version of Alamofire for Swift 2

Alamofire.request(.POST, urlString, parameters: parameters as? [String : AnyObject])
                


        
3条回答
  •  天命终不由人
    2020-12-08 14:35

    You can now achieve most of the required behaviour out of the box without the need for SwiftyJSON for example. My OAuthTokenResponse is a simple struct that is Codable. The Alamofire library 5.2.2 lets you respond using the '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)

    let request = AF.request(identityUrl, method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
        request
            .validate()
            .responseDecodable { (response:AFDataResponse) 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. Any errors will result in the error case being hit instead.

提交回复
热议问题