IOS AFNetworking automatically asks for a request when internet connection returns

Does AFNetworking for iOS support a solution to cache failed requests (for example due to no internet connection) and automatically retry the request when internet connection returns.

Thanks, Doreen

+3


source to share


3 answers


See the Network Reachability Manager section of the AFNetworking website. Using "Reachability" your handler will be called whenever the network availability changes. Just install setReachabilityStatusChangeBlock

for AFHTTPRequestOperationManager

(AFNetworking 2) or AFHTTPSessionManager

(AFNetworking 3):



AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];

[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    switch (status) {
        case AFNetworkReachabilityStatusReachableViaWWAN:
        case AFNetworkReachabilityStatusReachableViaWiFi:
            // do whatever you want when network is available
            break;
        case AFNetworkReachabilityStatusNotReachable:
        default:
            // do whatever you want when network is not available
            break;
    }
}];

[manager.reachabilityManager startMonitoring];

      

+1


source


As Matt said in AFNetworking issue # 393 , AFNetworking has no retry mechanism:

This is what several people asked for, but each of the use cases had surprisingly different requirements for behavior, which makes me think that a general solution that is useful for all relevant cases is not possible.

I am of the opinion that retrying the request is an application problem (or perhaps even something for the user initiator); this is not all that is difficult to implement on your own:



- (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


source


No, but you can find out in the failure block if the request has timed out. And you can send it in that case (like a retry counter of something like this).

0


source







All Articles