I\'m trying to send a HTTP request with NSURLSession. It works fine, but when the server doesn\'t respond I can\'t find where the HTTP error code is stored. The
The second parameter of the completionHandler is the NSURLResponse, which when doing a HTTP request, is generally a NSHTTPURLResponse. So, you'd generally do something like:
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:[self postRequestWithURLString:apiEntry parameters:parameters] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// handle basic connectivity issues here
if (error) {
NSLog(@"dataTaskWithRequest error: %@", error);
return;
}
// handle HTTP errors here
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(@"dataTaskWithRequest HTTP status code: %d", statusCode);
return;
}
}
// otherwise, everything is probably fine and you should interpret the `data` contents
NSLog(@"data: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
[dataTask resume];