MTurner MTurner - 3 months ago 26
iOS Question

AFNetworking - How to setup requests to be retried in the event of a timeout?

I have recently migrated from ASIHTTPRequest to AFNetworking, which has been great. However, the server that I am connecting with has some issues and sometimes causes my requests to timeout. When using ASIHTTPRequest it was possible to setup a retry count on a request in the event of a timeout using the following selector

-setNumberOfTimesToRetryOnTimeout:


This can be further referenced in this post, Can an ASIHTTPRequest be retried?

This is AFNetworking if you are unfamiliar
https://github.com/AFNetworking/AFNetworking#readme

I was unable to find an equivalent api in AFNetworking, has anyone found a solution for retrying network requests in the event of timeout using AFNetworking?

Answer

Matt Thompson developer of AFNetworking was kind enough to answer this for me. Below is the github link explaining the solution.

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

Basically, AFNetworking doesn't support this functionality. It is left to the developer to implement on a case by case basis as shown below (taken from Matt Thompson's answer on 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];
        }];
    }
}