简体   繁体   中英

iphone: NSURLCache on disk

I'm having trouble with caching URLResponses to disk. I want that because the data i'm downloading needs reloading when the expires-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 (eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM