【问题标题】:NSURLCache doesn't work (with Cache-Control = no-cache)NSURLCache 不起作用(使用 Cache-Control = no-cache)
【发布时间】:2014-01-16 14:02:10
【问题描述】:

我在 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. 如果不是,我应该使用什么解决方案来缓存服务器答案? (我无法在服务器端进行任何更改)

【问题讨论】:

  • “默认情况下,连接的数据根据​​请求的缓存策略进行缓存”在文档中。
  • 是的,默认情况下。但是我不使用默认的“NSURLRequestUseProtocolCachePolicy”,我使用“NSURLRequestReturnCacheDataElseLoad”,这意味着“使用缓存数据,忽略其年龄或到期日期”

标签: ios caching nsurlconnection nsurlcache


【解决方案1】:

在您的 Cache-Control 标头中已经清楚地说明了这一点:

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

这告诉客户端不要毫无疑问地缓存响应......

【讨论】:

  • 这意味着我不能将 NSURLCache 与这样的 http 标头一起使用?我的第二个问题呢?我应该改用什么缓存解决方案?
【解决方案2】:

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

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

首先你要准备cachedResponse,在这里你可以自己修改headers。

【讨论】:

    猜你喜欢
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2011-11-26
    • 2019-07-09
    • 1970-01-01
    相关资源
    最近更新 更多