SolvedAlamofire validate() "eats" response data

debugPrint(response) without validate():

[Request]: <NSMutableURLRequest: 0x10040ddd0> { URL: https://platform.devtest.ringcentral.com/restapi/oauth/token }
[Response]: <NSHTTPURLResponse: 0x10025f980> { URL: https://platform.devtest.ringcentral.com/restapi/oauth/token } { status code: 400, headers {
    Connection = "keep-alive";
    "Content-Language" = en;
    "Content-Length" = 83;
    "Content-Type" = "application/json;charset=UTF-8";
    Date = "Fri, 26 Aug 2016 15:03:27 GMT";
    RCRequestId = "3e87d7de-6b9e-11e6-a8f4-005056bb594d";
    RoutingKey = SJC11P01PAS01;
    Server = "nginx/1.8.0";
    "Www-Authenticate" = "Basic realm=\"RingCentral REST API\"";
    "X-LoadMetric" = 4;
} }
[Data]: 83 bytes
[Result]: SUCCESS: {
  "error" : "invalid_request",
  "error_description" : "Unsupported grant type"
}
[Timeline]: Timeline: { "Request Start Time": 493916605.929, "Initial Response Time": 493916607.145, "Request Completed Time": 493916607.146, "Serialization Completed Time": 493916607.146, "Latency": 1.217 secs, "Request Duration": 1.217 secs, "Serialization Duration": 0.000 secs, "Total Duration": 1.217 secs }

debugPrint(response) with validate():

[Request]: <NSMutableURLRequest: 0x10040a5b0> { URL: https://platform.devtest.ringcentral.com/restapi/oauth/token }
[Response]: <NSHTTPURLResponse: 0x100365bd0> { URL: https://platform.devtest.ringcentral.com/restapi/oauth/token } { status code: 400, headers {
    Connection = "keep-alive";
    "Content-Language" = en;
    "Content-Length" = 83;
    "Content-Type" = "application/json;charset=UTF-8";
    Date = "Fri, 26 Aug 2016 15:05:49 GMT";
    RCRequestId = "9328183a-6b9e-11e6-b36a-005056bb26b9";
    RoutingKey = SJC11P01PAS01;
    Server = "nginx/1.8.0";
    "Www-Authenticate" = "Basic realm=\"RingCentral REST API\"";
    "X-LoadMetric" = 4;
} }
[Data]: 83 bytes
[Result]: FAILURE: Error Domain=com.alamofire.error Code=-6003 "Response status code was unacceptable: 400" UserInfo={StatusCode=400, NSLocalizedFailureReason=Response status code was unacceptable: 400}
[Timeline]: Timeline: { "Request Start Time": 493916746.708, "Initial Response Time": 493916749.121, "Request Completed Time": 493916749.121, "Serialization Completed Time": 493916749.122, "Latency": 2.413 secs, "Request Duration": 2.413 secs, "Serialization Duration": 0.001 secs, "Total Duration": 2.414 secs }

So where has the following data gone:

{
  "error" : "invalid_request",
  "error_description" : "Unsupported grant type"
}

The data is very useful message from server. But validate() "eats" it.

25 Answers

✔️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?

Related Issues:

140
Alamofire “Use Legacy Swift Language Version” with pod 'Alamofire', '~> 4.0'
Have you tried this? http://stackoverflow.com/a/38466703/1054550 I have to convert my project from X...
65
Alamofire iOS 13.3.1 dyld: Library not loaded
Are you using a non-developer Apple ID to install the app to your phone? It looks like iOS 13.3.1 ha...
51
Alamofire Extra argument 'method' in call
I'm getting the same issue with the same error message (Extra argument 'method' in call) with correc...
43
Alamofire Sending GET with JSON in body gets Timeout error
I figured out my problem In my Router I had my GET requests using JSONEncoding: urlRequest = try JSO...
35
Alamofire Alamofire 4.3.0 setting timeout throws NSURLErrorDomain error
Hello I solved the problem with: I pupdated my question in StackOverflow I am using the version 4.3....
28
Alamofire Module compiled with Swift 4.2.1 cannot be imported by the Swift 5.0
I'm having almost the exact the same issue: Module compiled with Swift 4.2.1 cannot be imported by t...
16
Alamofire [WIP] Swift 3.0 Migration
install compatibility with cocoapods? @kcharwood EDIT: use Alamofire - Swift 3.0 The initial migrati...
14
Alamofire validate() "eats" response data
So to all of you convinced the data is gone...it's not debugPrint(response) without validate(): debu...
8
Alamofire Version 3.5 not found on Cocoapods Specs
Until this is resolved you can use the 3.5.0 release by specifying the tag directly pod 'Alamofire' ...
43
Moya Not able to get URLEncoding working correctly when there is "?" and the method is "POST"
try use this and url request will like this base_url/api/update-password?token=114149814189 ...
18
Moya How to send String JSON Array as parameter?
Here is an UNTESTED example that at least compiles. I want to send String JSON array as parameter bu...
9
Moya How do I create a path with a '?' within the string?
@pete183 Yes URLEncoding.default will put your parameters in the url 😉 Moya Version - 8.0.5 When I ...
6
Moya Moya support for Swift 4 with RxSwift ?
Hey again @aninhakrieger @linbx08 I am using the following pods ...
479
Carthage Carthage builds fail at xcrun lipo on Xcode 12 beta (3,4,5...)
Workaround that works with both Xcode 11 and 12 Works with all versions of Xcode 12 (except beta 1 a...
66
CocoaLumberjack Xcode 9 beta 3 breaks the new os_log logger
Getting the following errors DDOSLogger.m: DDOSLogger.m:58:17: Static_assert failed format argument ...
30
Carthage carthage build command complains about "Could not find any available simulators for iOS"
I have the exactly the same situation with xCode 10.2 my Carthage was outdated after update to 0.33 ...
30
Eureka PushRow - Prevent Nil
do the trick This may be a basic question - but for a PushRow - is there a way to make it to where i...
26
Carthage How: Please update to the latest Carthage version
This command updates brew itself and does not take formula names the command should be brew upgrade ...
25
Carthage Xcode 11.0 Beta 4 fails to archive Swift-containing frameworks w/ Bitcode · Workaround Available
To solve the issue create a workaround.xcconfig file This file can live elsewhere - like your deskto...
18
Eureka Xcode 11.4, error: Segmentation fault: 11 (in target 'Eureka' from project 'Eureka')
This compiler error isn't resolved in the final 11.4 release What's odd is that it only fails on the...
15
Eureka Fails to compile in Xcode 9
pod 'Eureka' :git => 'https://github.com/xmartlabs/Eureka.git' :branch => 'Xcode9-Swift4' does not w...
13
SideMenu iOS 13: menu opens on full screen
If you use storyboard click the Storyboard segue(the line connects view controllers) on the right pa...
8
SkeletonView Wrong skeleton view width on iPhone 8 plus
Ok I've found my problem I was calling showSkeleton in viewDidLoad Moving it to viewDidAppear fixed ...
8
Eureka Error: Duplicate tag when using custom object with PushRow
It works if you declare your class ServicePaymentRate to be CustomStringConvertible ...
6
Carthage Carthage doesn't read latest commit in local repository
Had the same problem with local repository what solved it is clearing cache rm -rf ~/Library/Caches/...
3
CoreStore Build fails on Xcode 8 / macOS Sierra (both for Swift 2.3 and 3)
Thank you to everyone who helped debug the problem here and over at the slack channel! I turned off ...
3
SkeletonView SkeletonView not working in TableViewCell with custom class
@pennywise94 I ran into this issue too; the giant solid happens because calling showSkeleton() on a ...
765
655
CocoaPods [error report] pod install /w m1 macbook
do you have a MacBook Pro with a M1 processor? this fixed my issue: Report What did you do? Run pod ...
392
CocoaPods NoMethodError - undefined method `size' for nil:NilClass
Also faced with this issue Fixed by updating flutter and cocoa pods to the latest version and then ...
247
CocoaPods pod install has bug
Did you try: sudo arch -x86_64 gem install ffi And run: arch -x86_64 pod install instead of pod inst...
186
CocoaPods CocoaPods was not able to update the master repo
Looks like your specs repo was edited at some point and now git can't update it ...
182
CocoaPods CocoaPods compatibility with Apple DTK (Apple Silicon)
For anyone else struggling with this issue I just found a way to solve it In addition to running ter...
175
CocoaPods Build issue with Xcode 12.3 - file not found #include "ruby/config.h"
I just updated to Xcode 12.3 and I am hitting this issue Seems like Xcode 12.3 broke the system ruby...
169
CocoaPods Unzip fail when zip contains chinese char on macOS 10.13
Maybe replace unzip with ditto: I have a SDK and there is a folder named FaceDistortion_20171205雪天的雪...
163
CocoaPods None of your spec sources contain a spec satisfying the dependencies
Did you note this part of the error message: Note: as of CocoaPods 1.0 pod repo update does not happ...
145
CocoaPods pod install fails with json error on Mac OS X 10.15
I did rm -rf ~/.cocoapods/repos/trunk/ After that it worked again. I've read and understood the CONT...
124
CocoaPods No such file or directory @ rb_sysopen -- AppCenter -- ReactNative
So I updated my appcenter dependencies from v2.4.0 to v2.5.0 and I'm having this issue again 🙄 Edit...
122
CocoaPods App Icons not included in build from Xcode 9
I have the same problem Report What did you do? Run project on device from Xcode 9 Beta 6 What did y...
113
CocoaPods Intermittent CDN issues
The workaround to get working locally during this outage or CDN issue - guessing a DNS change or som...
89
CocoaPods new Macbook M1 crash
As a temporary fix I've installed cocoapods using sudo arch -arch x86_64 gem install cocoapods then ...
83
CocoaPods Support multiple Swift versions on a per pod basis
this works: It's not pretty but will do until they update your pods to Swift 4. ...
80
CocoaPods pod update error with CDN
And? How to fix? gem install concurrent-ruby or gem update concurrent-ruby. I've read and understood...
71
CocoaPods Failed to build gem native extension. Header file missing,
I had the same problem on macOS Mojave 10.14.16 A few threads eventually lead me here which solved i...
54
CocoaPods I can not install pod files.
Nope Just do: Install ffi sudo arch -x86_64 gem install ffi Re-install dependencies arch -x86_64 pod...
52
CocoaPods CocoaPods1.9.0 cannot install on Mojave10.14.6
This should be re-opened I can repro on a clean Mojave The workaround is to run sudo gem install coc...
46
CocoaPods [Xcode 8 beta 2]: CopySwiftLibs for Pods framework fails with Mach-O header error
I've found a workaround Add the following lines to your Podfile: 🌈 I've read and understood the *CO...
45
CocoaPods FBSDKLoginKit can not find headers under 1.0.0
This appears to be some issue between CocoaPods and XCode I tried to reproduce the problem I was see...
40
CocoaPods Podfile without use_frameworks! triggers "deployment target" warnings in Xcode 10
For those wanting a quick fix: edit: updated snippet now supports the new generate_multiple_pod_proj...