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 third parameter of completionHandler
is just a very general NSError
. I read the reference of NSURLResponse
but found nothing.
NSURLSessionDataTask *dataTask =
[session dataTaskWithRequest:[self postRequestWithURLString:apiEntry parameters:parameters]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(!error) NSLog([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
];
[dataTask resume];
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];
Swift 3:
// handle basic connectivity issues here
guard error == nil else {
print("Error: ", error!)
return
}
// handle HTTP errors here
if let httpResponse = response as? HTTPURLResponse {
let statusCode = httpResponse.statusCode
if (statusCode != 200) {
print ("dataTaskWithRequest HTTP status code:", statusCode)
return;
}
}
if let data = data {
// here, everything is probably fine and you should interpret the `data` contents
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With