AFNetworking - 如何在超时的情况下设置要重试的请求?

时间:2012-08-31 18:47:02

标签: iphone ios ipad asihttprequest afnetworking

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

-setNumberOfTimesToRetryOnTimeout:

这篇文章可以在Can an ASIHTTPRequest be retried?

中进一步引用

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

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

4 个答案:

答案 0 :(得分:58)

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

答案 1 :(得分: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);
        }];
    }

答案 2 :(得分:2)

在我的情况下,我经常需要重试功能,因此我想出了这个重试政策类别,它可以帮助您解决 AFNetworking+RetryPolicy

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

答案 3 :(得分: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请求完成,您不必在每个请求方法中实现重试循环。