23

我最近从 ASIHTTPRequest 迁移到了 AFNetworking,这很棒。但是,我正在连接的服务器存在一些问题,有时会导致我的请求超时。使用 ASIHTTPRequest 时,可以使用以下选择器在超时的情况下设置请求的重试计数

-setNumberOfTimesToRetryOnTimeout:

这可以在这篇文章中进一步引用,可以重试 ASIHTTPRequest 吗?

如果您不熟悉,这是 AFNetworking https://github.com/AFNetworking/AFNetworking#readme

我在 AFNetworking 中找不到等效的 api,有没有人找到在使用 AFNetworking 超时的情况下重试网络请求的解决方案?

4

4 回答 4

59

AFNetworking 的开发人员 Matt Thompson 很友好地为我回答了这个问题。下面是解释解决方案的 github 链接。

https://github.com/AFNetworking/AFNetworking/issues/393

基本上,AFNetworking 不支持此功能。由开发人员根据具体情况实施,如下所示(取自 Matt Thompson 在 github 上的回答)

- (void)downloadFileRetryingNumberOfTimes:(NSUInteger)ntimes 
                              success:(void (^)(id responseObject))success 
                              failure:(void (^)(NSError *error))failure
{
    if (ntimes <= 0) {
        if (failure) {
            NSError *error = ...;
            failure(error);
        }
    } else {
        [self getPath:@"/path/to/file" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (success) {
                success(...);
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self downloadFileRetryingNumberOfTimes:ntimes - 1 success:success failure:failure];
        }];
    }
}
于 2012-09-06T23:26:49.540 回答
2

我在我的 ApiClient 类中实现了私有方法:

- (void)sendRequest:(NSURLRequest *)request successBlock:(void (^)(AFHTTPRequestOperation *operation, id responseObject))successBlock failureBlock:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failureBlock
{
    __block NSUInteger numberOfRetries = 3;
    __block __weak void (^weakSendRequestBlock)(void);
    void (^sendRequestBlock)(void);
    weakSendRequestBlock = sendRequestBlock = ^{
        __strong typeof (weakSendRequestBlock)strongSendRequestBlock = weakSendRequestBlock;
        numberOfRetries--;

        AFHTTPRequestOperation *operation = [self.httpManager HTTPRequestOperationWithRequest:request success:successBlock failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSInteger statusCode = [[[error userInfo] objectForKey:AFNetworkingOperationFailingURLResponseErrorKey] statusCode];

            if (numberOfRetries > 0 && (statusCode == 500 || statusCode == 502 || statusCode == 503 || statusCode == 0)) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                    strongSendRequestBlock();
                });
            } else {
                if (failureBlock) {
                    failureBlock(operation, error);
                }
            }
        }];

        [self.httpManager.operationQueue addOperation:operation];
    };

    sendRequestBlock();
}

使用示例:

- (void)getSomeDetails:(DictionaryResultBlock)block
    {
        if (!block) {
            return;
        }

        NSString *urlString = @"your url string";
        NSMutableURLRequest *request = [self.httpManager.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:urlString relativeToURL:self.defaultUrl] absoluteString] parameters:nil error:nil];

        // Configure you request here
       [request setValue:version forHTTPHeaderField:@"client-version"];

        NSMutableDictionary *bodyParams = @{};   
        [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:bodyParams options:0 error:nil]];

        [self sendRequest:request successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            id response = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            block(response, nil);
        } failureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            block(nil, error);
        }];
    }
于 2014-08-07T08:53:17.453 回答
2

就我而言,我经常需要重试功能,所以我想出了这个重试策略类别,它可以帮助你使用AFNetworking+RetryPolicy

对于AFNetworking 3.0,它可以很好地发挥作用。

于 2016-08-26T23:34:17.257 回答
1

根据您的回答,您可以通过使用将块作为参数的块来做一些更通用(和棘手)的事情:

typedef void (^CallbackBlock)(NSError* error, NSObject* response);
- (void) performBlock:(void (^)(CallbackBlock callback)) blockToExecute retryingNumberOfTimes:(NSUInteger)ntimes onCompletion:(void (^)(NSError* error, NSObject* response)) onCompletion {
    blockToExecute(^(NSError* error, NSObject* response){
        if (error == nil) {
            onCompletion(nil, response);
        } else {
            if (ntimes <= 0) {
                if (onCompletion) {
                    onCompletion(error, nil);
                }
            } else {
                [self performBlock:blockToExecute retryingNumberOfTimes:(ntimes - 1) onCompletion:onCompletion];
            }
        };
    });
}

然后围绕您的异步 HTTP 请求,如下所示:

[self performBlock:^(CallbackBlock callback) {

        [...]
        AFHTTPRequestOperationManager *manager = [WSManager getHTTPRequestOperationManager];
        [manager POST:base parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

            dispatch_async(dispatch_get_main_queue(), ^(void){
                    if (callback) {
                        callback(nil, responseObject);
                    }
                });

            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                if (callback) {
                    NSError* errorCode = [[NSError alloc] initWithDomain:AppErrorDomain code:[operation.response statusCode] userInfo:@{ NSLocalizedDescriptionKey :error.localizedDescription}];
                    callback(errorCode, nil);
                }
            }];

    } retryingNumberOfTimes:5 onCompletion:^(NSError *error,  NSObject* response) {
        //everything done
    }];

这样,重试等待 HTTP 请求完成,您不必在每个请求方法中实现重试循环。

于 2016-03-07T10:04:27.037 回答