Search code examples
iosobjective-c

NSURLResponse - How to get status code?


I have a simple NSURLRequest:

[NSURLConnection sendAsynchronousRequest:myRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    // do stuff with response if status is 200
}];

How do I get the status code to make sure the request was ok?


Solution

  • Cast an instance of NSHTTPURLResponse from the response and use its statusCode method.

    [NSURLConnection sendAsynchronousRequest:myRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
        NSLog(@"response status code: %ld", (long)[httpResponse statusCode]);
        // do stuff
    }];