I'm having trouble with caching URLResponses to disk. I want that because the data i'm downloading needs reloading when the ex开发者_如何转开发pires-tag in it's http-header is met, not earlier. Also, I want iPod touch-Users to be able to download the data once while online and then use it offline.
i'm doing this which works fine for caching things in memory but fails when relaunching the app:
NSURLRequest* menuRequest = [NSURLRequest requestWithURL:mensaURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
NSCachedURLResponse* cachedMenuResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:menuRequest];
if (cachedMenuResponse) {
// received data is a member of that class to which the asynchronous
// download writes and which is then being used in updateDataFromDownload
// to retrieve my data structure from the download.
self.receivedData = [NSMutableData dataWithData:[cachedMenuResponse data]];
[self updateDataFromDownload];
NSLog(@"using data from cache");
} else {
NSLog(@"opening connection");
[NSURLConnection connectionWithRequest:menuRequest delegate:self];
}
AFAIK NSURLRequest/NSURLConnection support caching to disk from iOS 5.
UPDATE: @Rob correctly states in the comments:
I've found that if (a) you use the default NSURLRequest cachePolicy of NSURLRequestUseProtocolCachePolicy; and (b) the response doesn't include the Cache-Control header, it won't cache to disk. If you use a cachePolicy of NSURLRequestReturnCacheDataElseLoad, or if the response from the server specifies a particular Cache-Control header (e.g. public, max-age=1835400), it will cache to persistent storage.
SDURLCache is a great subclass of NSURLCache for on disk caching, very performance focused.
Hope this helps, Vincent
精彩评论