35

in iOS, how can I receive the http status code (404,500 200 etc) for a response from a web server. I am assuming it's in the NSUrlConnectionDelegate.

Objective-C or Monotouch .NET answer ok.

Ian Vink
  • 66,960
  • 104
  • 341
  • 555

4 Answers4

88

Yes, you can get status code in delegate method -didRecieveResponse:

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
   NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
   int code = [httpResponse statusCode];
}
Vladimir
  • 170,431
  • 36
  • 387
  • 313
  • 2
    Note that, despite the use of dot notation, statusCode is not a property. – albertamg Aug 02 '11 at 21:32
  • 2
    @albertamg, oops indeed... thanks, will correct that to avoid confusion – Vladimir Aug 02 '11 at 21:33
  • 2
    I realise this is obvious, but I'll note it just for the sake of completeness: anywhere else that you get an `NSURLResponse` in response to a HTTP request (such as the completion handler of `sendAsynchronousRequest:queue:completionHandler:`, you can cast the `NSURLResponse` to an `NSHTTPURLResponse` in exactly the same way. – Mark Amery Aug 22 '13 at 09:12
11
NSHTTPURLResponse* urlResponse = nil;
NSError *error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];

The aSynchronous request should also have a way to get the NSHTTPURLResponse..

You get the status code like this:

int statusCode = [urlResponse statusCode];
int errorCode = error.code;

In the case of some much used error codes (like 404) it will get put in the error but with a different code (401 will be -1012).

John Ballinger
  • 7,380
  • 5
  • 41
  • 51
Manuel
  • 10,153
  • 5
  • 41
  • 60
  • 1
    There is no need to alloc error - just check if error is not null on return - if it isn't you should have an error code – gheese Oct 29 '13 at 23:06
  • Thanks heaps, that helped me. Thanks for the 401, that the error I was trying to trap. error.code = -1012 as you said. – John Ballinger Nov 01 '13 at 01:11
3

Here's how to do it in MonoTouch for .NET for those C# users. THis is in the NSUrlConnectionDelegate.

public override void ReceivedResponse (NSUrlConnection connection, NSUrlResponse response)
{
  if (response is NSHttpUrlResponse)
  {
    var r = response as NSHttpUrlResponse;
    Console.WriteLine (r.StatusCode);
   }
}
Ian Vink
  • 66,960
  • 104
  • 341
  • 555
1

Looking at this other stackoverflow question it looks like you can handle http status codes in the - (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)response delegate method:

- (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse*)response 
{
    if ([response isKindOfClass: [NSHTTPURLResponse class]])
        statusCode = [(NSHTTPURLResponse*) response statusCode];
}
Community
  • 1
  • 1
Carter
  • 3,053
  • 1
  • 17
  • 22