只需要离线缓存,而不考虑是否失效或过期的情况下(很少不考虑),可以直接进行本地存储和加载
1.NSURLCache设置
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024 * 1024
diskCapacity:1024 * 1024 * 1024
diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];
return YES;
}
2.初始化加载
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
_wkWeb = [[WKWebView alloc]initWithFrame:self.view.bounds];
_wkWeb.UIDelegate = self;
_wkWeb.navigationDelegate = self;
[self.view addSubview:_wkWeb];
_url = @"http://www.baidu.com";
NSURL *URL = [NSURL URLWithString:_url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10];
NSURLCache *cache = [NSURLCache sharedURLCache];
NSCachedURLResponse *cacheResponse = [cache cachedResponseForRequest:request];
if (!cacheResponse) {
[_wkWeb loadRequest:request];
}else{
[self.wkWeb loadData:cacheResponse.data MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:request.URL];
}
}
3.首次加载成功之后的存储
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
NSURLCache *cache = [NSURLCache sharedURLCache];
NSURL *url = [NSURL URLWithString:_url];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10];
NSCachedURLResponse *cacheResponse = [cache cachedResponseForRequest:request];
if (!cacheResponse) {
NSData *dataContent = [NSData dataWithContentsOfURL:url];
NSURLResponse *response = [[NSURLResponse alloc]initWithURL:url MIMEType:@"text/html" expectedContentLength:0 textEncodingName:@"UTF-8"];
cacheResponse = [[NSCachedURLResponse alloc]initWithResponse:response data:dataContent];
[cache storeCachedResponse:cacheResponse forRequest:request];
}
}
本文介绍了在不考虑缓存失效或过期的情况下,如何实现WKWebView的离线缓存功能。主要包括三步:1)配置NSURLCache;2)初始化并加载网页;3)首次加载成功后的本地存储操作。
511

被折叠的 条评论
为什么被折叠?



