我可以通过以下方式创建缓存条目:
[[NSURLCache sharedURLCache] storeCachedResponse:cachedURLresponse forRequest:request];
表示网址http://www.punkoffice.com/hello.html
如果我看到我的缓存条目存在后直接运行
NSLog(@"cache = %@",[[NSURLCache sharedURLCache] cachedResponseForRequest:request]);
我可以在SQLite数据库文件中看到它。
然而,当我使用完全相同的请求执行loadrequest时,如下所示:
[self.webView loadRequest:request]
找不到该请求的缓存条目,并创建一个新条目。它最终会覆盖我之前放入的缓存条目。
如何获取loadRequest以查看我使用storeCachedResponse存储的缓存条目?
(编辑) 这是我用来创建缓存条目的完整代码。我可以告诉这个位有效'因为它存在于缓存数据库中,我可以从cachedReponseForRequest中检索它
NSString *strURL = @"http://www.punkoffice.com/hello.html";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];
NSString *strData = @"<html><body>Some other content</body></html>";
NSData *dataContent = [strData dataUsingEncoding:NSUTF8StringEncoding];
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[NSURL URLWithString:strURL] MIMEType:@"text/html" expectedContentLength:[dataContent length] textEncodingName:nil];
NSCachedURLResponse *cachedURLresponse = [[NSCachedURLResponse alloc] initWithResponse:response data:dataContent];
我也尝试过添加标题:
NSDictionary *headers = @{@"Cache-Control":@"max-age=3600"};
NSHTTPURLResponse* httpResponse = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:strURL] statusCode:200 HTTPVersion:@"HTTP/1.1" headerFields:headers];
NSCachedURLResponse *cachedURLresponse = [[NSCachedURLResponse alloc] initWithResponse:httpResponse data:dataContent];
答案 0 :(得分:0)
创建 cachePolicy
时,您需要指定 NSURLRequest
。
+ (id)requestWithURL:(NSURL *)theURL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval
cachePolicy的值应为NSURLRequestReturnCacheDataElseLoad。
<强> NSURLRequestReturnCacheDataElseLoad 强>
指定现有的缓存 数据应该用于满足请求,无论其年龄或年龄 截止日期。如果缓存中没有现有数据 对应请求,数据从始发加载 源。
为了利用NSURLCache,必须初始化并设置共享URL缓存。
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
diskCapacity:20 * 1024 * 1024
diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];
您还应该确保响应包含Cache-Control HTTP标头。此标头必须存在于服务器的响应中,以启用客户端的HTTP缓存。
答案 1 :(得分:0)
我遇到了同样的问题。要解决这个问题,我已经这样做了。
NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
if (cachedResponse) {
[myWebView loadData:cachedResponse.data MIMEType:cachedResponse.response.MIMEType textEncodingName:cachedResponse.response.textEncodingName baseURL:request.URL];
}
else{
[myWebView loadRequest:request];
}
不确定,但在我看来,loadRequest
的{{1}}方法始终忽略UIWebView
并始终尝试连接到cachePolicy
的服务器,而不是查看缓存。