1
votes

I set up NSURLCache in my AppDelegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:50 * 1024 * 1024
                                                     diskCapacity:50 * 1024 * 1024
                                                         diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];

Then I'm trying to use it with cachePolicy:NSURLRequestReturnCacheDataElseLoad

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:getUrl
                                                       cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                                   timeoutInterval:timeInterval];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];

But it doesn't work at all (it requests server every time and don't even try to use cache).

I checked the headers in the server response, here it is:

"Cache-Control" = "no-cache, no-store, max-age=0, must-revalidate";
"Content-Encoding" = gzip;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sun, 29 Dec 2013 15:13:12 GMT";
Expires = "Fri, 01 Jan 1990 00:00:00 GMT";
P3P = "CP=\"NOI DSP COR NID ADMa OPTa OUR NOR\"";
Pragma = "no-cache";
Server = QRATOR;

From the Apple Documentation:
The NSURLRequestReturnCacheDataElseLoad cache policy causes the URL loading system to use cached data, ignoring its age or expiration date, and to load the data from the originating source only if there is no cached version.

My questions are:

  1. Should it work (by work I mean to cache server response) with "Cache-Control" = "no-cache, no-store, max-age=0, must-revalidate" in the response header ?

  2. If not, what solution should I use to cache server answers ? (I can't make any changes on the server side)

2
"By default, the data for a connection is cached based on the request’s cache policy" in docs.iMom0
Yes, by default. But I don't use default "NSURLRequestUseProtocolCachePolicy", I use "NSURLRequestReturnCacheDataElseLoad", which imply "use cached data, ignoring its age or expiration date"n0_quarter

2 Answers

1
votes

It's spelled out pretty clearly in your Cache-Control header:

"Cache-Control" = "no-cache, no-store, max-age=0, must-revalidate";

That tells the client NOT to cache the response in no uncertain terms...

1
votes

You can manually write object to cache:

NSURLCache *sharedCache = [NSURLCache sharedURLCache];
[sharedCache storeCachedResponse:cachedResponse forRequest:request];

First you have to prepare cachedResponse, where you can modify headers by yourself.