I've configured a memory and disk cache in my App Delegate but it does not seem like the cache is being used - it seems to go to the network every time. Is there an easy way to check if data is being cached and then retrieved on subsequent requests? Is setting up the cache all I have to do? Do I need to explicitly check the cache by calling cachedResponseForRequest each time or anything like that? Does it work on the simulator? My deployment target is iOS 6.
Thanks.
A couple of observations:
The request must be one that can be cached (e.g. http or https, but not ftp).
The response must generate the headers that indicate that indicate that the response can be cached. Notably, it must set Cache-Control. See NSHipster's discussion on NSURLCache.
For example, when downloading an image
<?php
$filename = "image.jpg";
$lastModified = filemtime($filename);
$etagFile = md5_file($filename);
header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastModified) . ' GMT');
header('Etag: "' . $etagFile . '"');
header('Content-Type: image/jpeg');
header('Cache-Control: public, max-age=1835400');
header('Content-Length: ' . filesize($filename));
readfile($filename);
?>
The response must satisfy some poorly documented rules (e.g. the response cannot exceed 5% of the total persistent NSURLCache). For example, you can place the following in the app delegate's didFinishLaunchingWithOptions:
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity: 5 * 1024 * 1024
diskCapacity:20 * 1024 * 1024 diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];
That sets a memory cache of 5mb and a persistent cache of 20mb.
For the sake of completeness, I'll state the obvious, that when creating NSURLRequest, a NSURLRequestCachePolicy of NSURLRequestReloadIgnoringLocalCacheData would prevent the cache from being used even if the response was previously cached.
In the same category of stating the obvious, a connection:willCacheResponse: method that returned nil would prevent the response from being cached.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With