开发者

NSUrlConnectionDelegate - Getting http status codes

开发者 https://www.devze.com 2023-03-25 15:56 出处:网络
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.

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 Monotouc开发者_JAVA技巧h .NET answer ok.


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];
}


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).


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);
   }
}


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];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消