简体   繁体   中英

NSURLCache doesn't work (with Cache-Control = no-cache)

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)

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...

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.

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