Alamofire Parse Response Data when verification fails

Therefore, the API I work with sometimes sends an error message to the response body when the request fails. It is located at response.data. Sometimes it is JSON, sometimes it is a string. I use the method validate, so result.valuethere is nilwhen an error occurs.

Is there a way for Alamofire to serialize data from NSData to a string or for JSON before [ String : AnyObject ], as if this answer were successful?

I would like to use the validate method.

EDIT: Here is the link to the feature request that I started in the Alamofire GitHub project.

https://github.com/Alamofire/Alamofire/issues/1459

+5
source share
2 answers

. Alamofire 4. Alamofire 3 response.data , . Alamofire 4 , , response.data , Error, .

, , , ( ). , , response.data, . , . , OAuth2 , .

+4

Swift 4

, json.

import Alamofire
import SwiftyJSON

Alamofire.request("http://domain/endpoint", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
    .validate()
    .responseJSON(completionHandler: { response in
        if let error = response.error {
            if let data = response.data {
                if let errorString = String(bytes: data, encoding: .utf8) {
                    print("Error string from server: \(errorString)")
                } else {
                    print("Error json from server: \(JSON(data))")
                }
            } else {
                print("Error message from Alamofire: \(error.localizedDescription)")
            }

        } 
        guard let data = response.result.value else {
            print("Unable to parse response data")
            return
        }
        print("JSON from server: \(JSON(data))")
    })
0

Source: https://habr.com/ru/post/1653628/


All Articles