繁体   English   中英

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

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

我在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文档中
NSURLRequestReturnCacheDataElseLoad高速缓存策略使URL加载系统使用高速缓存的数据,而忽略其使用期限或到期日期,并且仅当没有高速缓存的版本时才从原始源加载数据。

我的问题是:

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

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

在Cache-Control标头中清楚地阐明了这一点:

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

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

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

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

首先,您必须准备cachedResponse ,在这里您可以自己修改标头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM