views:

334

answers:

1

Hi,

I'm writing an application that connect with a server using NSURLConnection.

In the delegate method didreceiveresponse:, if the status code is 404, I cancel the connection and I would like to show a message with a custom error that is generated in the server.

The problem is that from response object, I only can get statuscode, headers, mimetype... but no body. How do I get the body message from NSURLResponse?

Thank you!

A: 

The NSURLConnection class does not have any methods of its own to return the http response code so treats a 404 as a successful response - which I suppose it is as a connection was made and something (the 404 page) was returned.

The trick to see if the response was a 200 OK or 404 NOT FOUND is to cast the NSURLResponse to a NSHTTPURLResponse and then use that classes methods to look for the http response code.

Try something like this:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

// cast the response to NSHTTPURLResponse so we can look for 404 etc
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

if ([httpResponse statusCode] >= 400) {
    // do error handling here
    NSLog(@"remote url returned error %d %@",[httpResponse statusCode],[NSHTTPURLResponse localizedStringForStatusCode:[httpResponse statusCode]]);
} else {
    // start recieving data
}

}

hope this helps. Rick

Rick