Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLCache returning nil when trying to access cached request from disk

I am trying to use the disk based url cacing built in to iOS 5. I have a json feed which i want to load and then cache, so its instantly loaded the next time a user uses the app. The cache.db file is successfully created and if i open it in a sqlite-editor i can fetch out the data.

I am using AFNetworking

NSURL *url = [NSURL URLWithString:@"http://myurl.com/json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

NSLog(@"%d before call",[[NSURLCache sharedURLCache] currentDiskUsage]);  // logs 0 bytes
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// is successfully loading JSON and reading it to a table view in a view
}failure:nil];

NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request] 
// this returns nil, and can't load the request from disk.

In the cache response block, strangely the cache is now working, and successfully gets the cacheurl request from memory.

[operation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
        NSCachedURLResponse *cachedResponse_ = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
        NSLog(@"%d AFTER CACHE",[[NSURLCache sharedURLCache] currentDiskUsage]);
        // this writes out 61440
        return cachedResponse;
    }];

How can i load the cached URL request from disk the next time i start the app?

like image 570
bogen Avatar asked Nov 09 '12 09:11

bogen


1 Answers

When you attempt to fetch the cached response in your first code section (line 9), the request has not completed yet.

-[AFJSONRequestOperation JSONRequestOperationWithRequest:success:failure:] is asynchronous, so nothing will be stored in the cache until the request completes. If you try to fetch the cached response inside the success block (or in a cache response block, as you did in your second code section), it should work correctly.

As to your second question, you can't guarantee that the data will be cached by NSURLCache, even if your Cache-Control headers state that your content shouldn't expire until far in the future. The cache file is always stored in your app's Caches directory, which can be cleared by iOS at any time if it thinks it needs to free up disk space.

If you need to make sure your JSON data is always available, save it yourself in your app's Library/Application Support directory, ideally with the NSURLIsExcludedFromBackupKey specified (unless your app truly cannot function without the data).

like image 151
jatoben Avatar answered Oct 18 '22 11:10

jatoben