Search code examples
ioscachingasihttprequest

ASIHTTPRequest Caching Not working


I'm not getting cached results using the ASIHTTPRequest Cache functionality. I followed the directions from documentation. When I have internet access, the below works perfectly. At that point, I will turn on Airplane mode and close the app from multi-tasking. When i do this, I get no asynchronous call to requestFinished. I have tried a bunch of the caching policies but that doesn't seem to do it. Does anyone have any ideas?

Goal: To be able to get a cached JSON response with no internet connection (after successfully loading from internet once).

- (void)viewDidLoad
{
    if (!networkQueue) {
        networkQueue = [[ASINetworkQueue alloc] init];
    }
    [networkQueue reset];
    [networkQueue setRequestDidFinishSelector:@selector(imageFetchComplete:)];
    [networkQueue setRequestDidFailSelector:@selector(imageFetchFailed:)];
    [networkQueue setShowAccurateProgress:true];
    [networkQueue setDelegate:self];

    //Turn on default caching
    [ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]];

    [self loadData];
    [super viewDidLoad];
}

-(IBAction)loadData
{
    NSURL *url = [NSURL URLWithString:@"http://SOME_JSON_URL"];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
    [request startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    if ([request didUseCachedResponse])
    {
        NSLog(@"Did use cache!");   
    }

    NSString *responseString = [request responseString];
    NSLog(@"%@", responseString);
}

Solution

  • This looks like ASIHTTPRequest thinks your data is expired. You can try to override expiry settings and see how it works:

    [[ASIDownloadCache sharedCache] setShouldRespectCacheControlHeaders:NO];
    [request setCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];
    

    Of course this is not optimal, as there are good reasons to use cache expiry. However it may lead you on the right track. If it is indeed an expiry issue, maybe you can make sure that the cache settings from the server side are adapted.

    A good cache policy may be the one stated in the documentation:

    [request setCachePolicy:ASIAskServerIfModifiedCachePolicy|ASIFallbackToCacheIfLoadFailsCachePolicy];