0
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{

    NSDictionary * dictionary = nil;
    NSError * returnError = nil;
    NSString * errorCode = nil;
    NSString * errorText = nil;
    NSInteger newErrorCode = 0;

    if([data length] >= 1) {
        dictionary = [NSJSONSerialization JSONObjectWithData: data options: 0 error: nil];
    }

    if(dictionary == nil) {

        newErrorCode = -1;
        errorText = @"There was an unexpected error.";
        NSMutableDictionary* details = [NSMutableDictionary dictionary];
        [details setValue: errorText forKey: NSLocalizedDescriptionKey];
        returnError = [NSError errorWithDomain: AppErrorDomain code: newErrorCode userInfo: details];

        responseHandler(nil, returnError);

        return;
    }

    NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];

    if(statusCode != 200)
    {
        if(dictionary != nil) {
            if([dictionary objectForKey: @"error_code"] != nil) {
                errorCode = [dictionary objectForKey: @"error_code"];
            }

            if([dictionary objectForKey: @"error_description"] != nil) {
                errorText = [dictionary objectForKey: @"error_description"];
            }
        }

        if(errorCode == nil)
        {
            newErrorCode = UnexpectedError;

            errorText =  NSLocalizedString(@"There was an unexpected error.", @"There was an unexpected error.");

        }
        else {
            newErrorCode = [errorCode intValue];
        }

        NSMutableDictionary* details = [NSMutableDictionary dictionary];
        [details setValue: errorText forKey: NSLocalizedDescriptionKey];
        returnError = [NSError errorWithDomain: APPErrorDomain code: newErrorCode userInfo: details];
    }

    responseHandler(dictionary, returnError);

    return;

}];

上記の非同期ネットワーク呼び出しでは、ステータス コードが 200 でないかどうかを確認し、それがエラーであると想定しています。IOS のネットワーク呼び出しでエラー/データ処理を処理する正しい方法はありますか?

非同期リクエストからの NSError は、http ステータス コードが 200 でない場合は常に非 nil であり、200 の場合は nill であると常に想定できますか?

4

1 に答える 1