Search code examples
iosafnetworkingafnetworking-2

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


Solution

  • See the Network Reachability Manager section of the AFNetworking site. By using "Reachability", your handler will be called whenever the network availability changes. Just set the setReachabilityStatusChangeBlock of the 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];