dorin dorin - 3 months ago 42
iOS Question

iOS AFNetworking automatically retry request when the internet connection is back

Does AFNetworking for iOS offer a solution to cache failed requests (e.g due to no internet connection) and automatically retry the request when the internet connection is back.

Thanks,
Dorin

Rob Rob
Answer

See the Network Reachability Manager section of the AFNetworking site. By using "Reachability", your handler will be called whenever the network availability changes.

NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];

NSOperationQueue *operationQueue = manager.operationQueue;
[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];