NSURLCache returns zero when trying to access a cached request from disk

I'm trying to use a disk-based binding built into iOS 5. I have a json channel that I want to download and then cache, so that it loads instantly the next time the user uses the application. The cache.db file was created successfully, and if I open it in the sqlite editor, I can extract 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, strange, the cache now works and successfully receives a cache 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 a cached url request from disk the next time the application starts?

+6
source share
1 answer

When you try to get a cached response in your first section of code (line 9), the request is not yet complete.

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

As for your second question, you cannot guarantee that the data will be cached by NSURLCache, even if your Cache-Control headers state that your content should not expire to the end in the future. The cache file is always stored in the Caches application directory, which can be cleared by iOS at any time if it believes that it needs to free up disk space.

If you need to make sure that JSON data is always available, save it yourself in your Library/Application Support directory, ideally with the NSURLIsExcludedFromBackupKey specified (if your application really cannot function without data).

+1
source

All Articles