NSURLCache不起作用(使用Cache-Control = no-cache)

时间:2013-12-29 15:31:21

标签: ios caching nsurlconnection nsurlcache

我在AppDelegate中设置了NSURLCache:

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

然后我尝试将它与cachePolicy一起使用:NSURLRequestReturnCacheDataElseLoad

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

但它根本不起作用(它每次都请求服务器,甚至不尝试使用缓存)。

我检查了服务器响应中的标头,这里是:

"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;

来自Apple Documentation
    NSURLRequestReturnCacheDataElseLoad缓存策略使URL加载系统使用缓存数据,忽略其年龄或到期日期,并且仅在没有缓存版本时才从原始源加载数据。

我的问题是:

  1. 它应该工作(通过工作我的意思是缓存服务器响应),响应头中的“Cache-Control”=“no-cache,no-store,max-age = 0,must-revalidate”?

  2. 如果没有,我应该使用什么解决方案来缓存服务器答案? (我无法在服务器端进行任何更改)

2 个答案:

答案 0 :(得分:1)

在Cache-Control标题中清楚地说明了这一点:

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

告诉客户不要以不确定的方式缓存响应......

答案 1 :(得分:1)

您可以手动将对象写入缓存:

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

首先,您必须准备cachedResponse,您可以自行修改标题。

相关问题