Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFNetworking (AFHttpClient) offline mode not working with NSURLRequestReturnCacheDataDontLoad policy

I am using AFNetworking in my app and try to make it work in the offline mode by use the cached data if available.

I expected after I set the request cache policy to NSURLRequestReturnCacheDataDontLoad, getPath:parameters:success:failure: will success with the cached data while offline. However, even if there are data in the cache (I verified by check the cache with the code), getPath will simply fail in airplane mode.

There was a thread in AFNetworking github: https://github.com/AFNetworking/AFNetworking/issues/378 But seemed the issue is not addressed at all. The author of AFNetworking simply point to Apple's document, and it said:

NSURLRequestReturnCacheDataDontLoad Specifies that the existing cache data should be used to satisfy a request, regardless of its age or expiration date. If there is no existing data in the cache corresponding to a URL load request, no attempt is made to load the data from the originating source, and the load is considered to have failed. This constant specifies a behavior that is similar to an “offline” mode.

As Apple said, NSURLRequestReturnCacheDataDontLoad is exactly designed for offline mode.

I am testing in iOS6, I tested with both NSURLCache and SDURLCache, all have the same result.

The request failed, the error message:

2012-12-22 03:11:18.988 Testapp[43692:907] error: Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo=0x211b87c0 {NSErrorFailingURLStringKey=http://Testapp.com/api/v1/photo/latest/, NSErrorFailingURLKey=http://Testapp.com/api/v1/photo/latest/, NSLocalizedDescription=The Internet connection appears to be offline., NSUnderlyingError=0x211b9720 "The Internet connection appears to be offline."}

like image 609
Robert Mao Avatar asked Dec 22 '12 11:12

Robert Mao


1 Answers

Turned out, it's a bug in iOS 6.

There is a discussion thread in AFNetworking exactly for this problem: https://github.com/AFNetworking/AFNetworking/issues/566

Thanks for guykogus' tips and experiments on this issue. I spent a night on this issue!

A summarized work around is read the response from cache, instead of use NSURLRequestReturnCacheDataDontLoad policy:

NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
if (cachedResponse != nil &&
    [[cachedResponse data] length] > 0)
{
    // Get cached data
    ....
}
like image 111
Robert Mao Avatar answered Oct 05 '22 17:10

Robert Mao