Handle HTTP error with NSURLSession?

前端 未结 5 1307
挽巷
挽巷 2021-01-07 16:33

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

5条回答
  •  滥情空心
    2021-01-07 17:10

    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];
    

提交回复
热议问题