28

I need to check and evaluate the HTTP Status Codes in my iPhone app. I've got an NSURLRequest object and an NSURLConnection that successfully (I think) connect to the site:

// create the request
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]
                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                    timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    // Create the NSMutableData that will hold
    // the received data
    // receivedData is declared as a method instance elsewhere
    receivedData=[[NSMutableData data] retain];
} else {
    // inform the user that the download could not be made
}

I got this code here: https://web.archive.org/web/20100908130503/http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html

But it doesn't (as far as I can see) say anything about accessing HTTP Status codes.

How to make a connection to a site and then check the HTTP Status Codes of that connection?

Cœur
  • 37,241
  • 25
  • 195
  • 267
cmcculloh
  • 47,596
  • 40
  • 105
  • 130

1 Answers1

76

This is how I do it:

    #pragma mark -
    #pragma mark NSURLConnection Delegate Methods
    - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
         NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
         int responseStatusCode = [httpResponse statusCode];
    }

But I'm using an asynchronous NSURLConnection, so this may not help you. But I hope it does anyway!

Rob
  • 25,984
  • 32
  • 109
  • 155
  • This did accomplish what I needed. The only problem is that if the URL/IP Addy doesn't exist, no response is received, so the app just hangs there forever. I'm currently looking into a way to address this... any suggestions would be appreciated... – cmcculloh May 28 '09 at 15:39
  • 3
    Look at the Reachabilty code from Apple. Only use the notification method though (not enabled in the code by default, see the comments in the init method) and always set the host you intend to check. http://stackoverflow.com/questions/477852/checking-for-internet-connectivity-in-objective-c – Kendall Helmstetter Gelner May 28 '09 at 21:44