我正在尝试从 NSURLCache 获取之前缓存的信息。使用此代码:
NSString *theCompleteURL = @"http://192.168.1.2:8080/api/endpoint.json";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:theCompleteURL]];
NSCachedURLResponse *response = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
if (response) {
NSLog(@"Cached data found");
}
else {
NSLog(@"Cached data not found");
}
但我总是从方法 cachedResponseForRequest 得到 nil 作为对“response”变量的响应。
我确信数据在缓存中,因为我在我的应用程序的 Cache.db 文件中检查了它,从 cfurl_cache_response 表中得到了这个结果:
sqlite> select * from cfurl_cache_response;
1|0|1875686237|0|http://192.168.1.2:8080/api/endpoint.json|2014-01-09 11:55:17|
sqlite>
在 ApplicationDelegate 中,NSURLCache 配置为:
NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:5 * 1024 * 1024
diskCapacity:40 * 1024 * 1024
diskPath:nil];
[NSURLCache setSharedURLCache:cache];
知道缓存会发生什么吗?
我端点的 header 如下所示:
$ curl -I http://192.168.1.2:8080/api/endpoint.json
HTTP/1.1 200 OK
Content-Length: 1385
Expires: Thu, 01 Dec 2020 16
00: 00 GMT
Content-Type: application/json;charset=utf-8
ETag: "3e86-410-3596fbbc"
Cache-Control: max-age=3600
Connection: keep-alive
Server: thin 1.5.1 codename Straight Razor
$
最佳答案
这可以通过与响应关联的 header 来解释,特别是 Cache-control
和 Etag
字段。另见 here :
13.1.3 Cache-control Mechanisms
The basic cache mechanisms in HTTP/1.1 (server-specified expiration times and validators) are implicit directives to caches. In some cases, a server or client might need to provide explicit directives to the HTTP caches. We use the Cache-Control header for this purpose.
The Cache-Control header allows a client or server to transmit a variety of directives in either requests or responses. These directives typically override the default caching algorithms. As a general rule, if there is any apparent conflict between header values, the most restrictive interpretation is applied (that is, the one that is most likely to preserve semantic transparency).
13.3.2 Entity Tag Cache Validators
The ETag response-header field value, an entity tag, provides for an "opaque" cache validator. This might allow more reliable validation in situations where it is inconvenient to store modification dates, where the one-second resolution of HTTP date values is not sufficient, or where the origin server wishes to avoid certain paradoxes that might arise from the use of modification dates.
关于ios - NSURLCache cachedResponseForRequest 不检索缓存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21023396/