Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle HTTP error with NSURLSession?

Tags:

http

ios

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];
like image 200
Lai Yu-Hsuan Avatar asked Mar 05 '14 18:03

Lai Yu-Hsuan


2 Answers

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];
like image 101
Rob Avatar answered Nov 13 '22 12:11

Rob


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
}
like image 9
MrAn3 Avatar answered Nov 13 '22 13:11

MrAn3