NSURLCache on OSX

Peter Steinberger wrote an article about NSURLCache Uses a Disk-cache as of iOS5. Let us look, how NSURLCache works on OSX, because it seems like NSURLCache doesn’t work out of the box the same way as in iOS.

NSURLCache implements caching of responses made with a NSURLConnection. This is handy for e.g. image caching or cache website ressources. Before OSX Lion, NSURLCache saved the requests in memory and not permantly on the hard disk. As of Lion, NSURLCache automatically saves responses to disk.

After playing with NSURLCache, I’ve found out that we will not get caching to disk without any initialization procedure like in iOS5. In the Application Delegates applicationDidFinishLaunching: method we have to initialize a new NSURLCache and set the memory and disk capacity as well as the appropriate cache path:

- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
NSString *cachePath = [basePath stringByAppendingPathComponent:APP_SUPPORT_DIR_NAME];
NSURLCache *urlCache = [[NSURLCache alloc] initWithMemoryCapacity:1024*1024 // 1MB mem cache
diskCapacity:1024*1024*1024 // 1GB disk cache
diskPath:cachePath];
[NSURLCache setSharedURLCache:urlCache];
}

This is the procedure you we to do to on the NSURLCache side. Certainly there are times that you don’t want to save specific request, like in big downloads that we want to manually save to the harddisk. In this situations we might want to override the NSURLConnection delegate connection:willCacheResponse: method and return nil.

I will not go deeper into this topic, because the rest doesn’t differ between OSX and iOS. You will find further information about e.g. the creation of NSURLRequests that will be cached in the NSURLCache or concrete implementation details of the connection:willCacheResponse: method mention above, in the article from Peter Steinberger, NSURLCache Uses a Disk-cache as of iOS5.