SolvedAlamofire validate() "eats" response data
✔️Accepted Answer
So to all of you convinced "the data is gone"...it's not.
Response Struct
The data is ALWAYS passed back to you in EVERY response serialization closure as part of the Response
object in AF 3. Take a look at the Response
struct:
/// Used to store all response data returned from a completed `Request`.
public struct Response<Value, Error: ErrorType> {
/// The URL request sent to the server.
public let request: NSURLRequest?
/// The server's response to the URL request.
public let response: NSHTTPURLResponse?
/// The data returned by the server.
public let data: NSData?
/// The result of response serialization.
public let result: Result<Value, Error>
/// The timeline of the complete lifecycle of the `Request`.
public let timeline: Timeline
}
Is the data
property not clear? Did anyone think to check it? Notice the [Data]: 83 bytes
that keep getting printed out when you use debugPrint
@tylerlong and @gchaturvedi? Come on guys, help yourselves out a bit here...
Validation
To your last point @tylerlong:
It does contain some quite useless message like Response status code was unacceptable: 400 which is not the message from the server at all.
How is that "useless"? The error tells you "exactly" what went wrong with the request. You told Alamofire to validate the request, it did and told you why it failed.
History Lesson
If you don't run validation on the response, you're saying that as long as the request didn't encounter an error, I consider the request a success and I'm going to handle the result in my response serializer. However, the validation APIs exist if you decide that you'd prefer to have Alamofire hand you an error in your response serializer if the response wasn't formatted the way you wanted. This has always been a choice up to the user.
Now at some point in the Alamofire releases, we realized that you always want to have access to the data that came back from the server in a success or failure case for the exact reasons you have all put in here. It can be useful! So as you can see, all the response serializers hand you back the server data directly regardless of what the result type is.
Hopefully that helps.
Cheers.
Other Answers:
@tylerlong Try this
if let responseData = response.data {
let responseDataString = NSString(data: responseData, encoding:NSUTF8StringEncoding)
print(responseDataString)
}
Does that print the JSON, you expected?
debugPrint(response)
withoutvalidate()
:debugPrint(response)
withvalidate()
:So where has the following data gone:
The data is very useful message from server. But
validate()
"eats" it.