94

I see that there is a list of accepted http status codes that I can modify, but I think it would be cleaner if I can get the http status code in the failure block ..

Ok, found the answer with the operation object

failure:^(AFHTTPRequestOperation *operation, NSError *error){ 
        NSLog(@"error code %d",[operation.response statusCode]);
}];

6 Answers 6

136

Ok, found the answer with the operation object

failure:^(AFHTTPRequestOperation *operation, NSError *error){ 
       NSLog(@"error code %d",[operation.response statusCode]);
}];
2
  • This might be also helpful [operation.request HTTPMethod]
    – defvol
    Nov 30, 2012 at 18:06
  • 2
    I know this is old, but @wilhelmbot -- HTTPMethod would give you something like GET/POST/PUT... etc, probably not helpful for checking response status. Aug 8, 2013 at 13:44
112

In newer versions of AFNetworking, you can retrieve the response object from the error:

[[[error userInfo] objectForKey:AFNetworkingOperationFailingURLResponseErrorKey] statusCode]

This is handy if you're doing error handling further up the line and don't want to pass around the response object.

1
  • You might need to get the underlying error first. NSError *underlyingError = error.userInfo[@"NSUnderlyingError"]
    – Onato
    Oct 6, 2014 at 9:33
19

For AFNetworking 3.0, use

failure:^(NSURLSessionTask *operation, NSError *error) {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)operation.response;
    httpResponse.statusCode;
    NSLog(@"status code: %li", (long)httpResponse.statusCode);
}
13

NSInteger operationStatusCode = [operation.error code];

NSInteger httpStatusCode = operation.response.statusCode;

If the requests were cancelled/unreachable/timeout, httpStatusCode will be always 0.

Alternatively you can identify the issue by understanding the operationStatusCode. It is a NSError Object.

  • If it cannot reach/timeout/no network to process request, the operationStatusCode will be -1009.
  • If you cancel the operations queue the operationStatusCode will be -999.

You can check all other NSError codes and their descriptions in Apple's documentation

7

I've been able to get the status code with Swift 3:

((error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey])
    as! HTTPURLResponse).statusCode
0

It's work for me Add below line to your request

manager.requestSerializer = [AFJSONRequestSerializer serializer];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.