ios 缓存 WKWebView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30864893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cache for WKWebView
提问by user553536
I am having trouble with my custom internet browser. I am using WKWebView. I have tabs in my app. If I click on a tab new NSURLRequest loads in the WKWebView. I need to implement a cache. If a user presses on a tab, I'd prefer to load a cache data instead of new. Unfortunately this code doesn't work:
我的自定义 Internet 浏览器有问题。我正在使用 WKWebView。我的应用程序中有标签。如果我单击一个选项卡,WKWebView 中会加载新的 NSURLRequest。我需要实现一个缓存。如果用户按下选项卡,我更愿意加载缓存数据而不是新数据。不幸的是,这段代码不起作用:
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:0.0];
[self.webView loadRequest:request];
Can you guide me on how to implement cache for WKWebView?
你能指导我如何为 WKWebView 实现缓存吗?
回答by Dreaming In Binary
If you used NSURLRequestUseProtocolCachePolicy
, which is the default, there shouldn't be anything else you need to do. This policy will automatically look at the response from the server to decide whether or not it should actually go and grab the data again.
如果您使用了NSURLRequestUseProtocolCachePolicy
,这是默认设置,则您无需执行任何其他操作。此策略将自动查看来自服务器的响应,以决定它是否真的应该再次获取数据。
If the server uses Cache-Control HTTP headers and sets the max age for its responses, NSURLSession will respect this and return cached responses before they expire.
如果服务器使用 Cache-Control HTTP 标头并为其响应设置最大年龄,NSURLSession 将尊重这一点并在它们过期之前返回缓存的响应。
回答by Durai Amuthan.H
I typically will load from a server if I have internet connectivity. Otherwise, I load from the cache.
如果我有互联网连接,我通常会从服务器加载。否则,我从缓存加载。
if reachability.isReachable {
urlRequestCache=NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10)
}
else {
urlRequestCache = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 60)
}
theWebView.loadRequest(urlRequestCache)