WKWebView 缓存清理的实现

引言:

WKWebView 是iOS8之后出现的,相较于 UIWebView,WKWebView占用的内存更小,还有一些其他的优化。但是如果我们不去主动清理webView产生的缓存,两者都会存在缓存这个问题。比如说一个网页改了一些内容,如果不清理缓存,可能很长一段时间我们都没办法看到新的内容,唯一的办法是卸载重装。

为了能让用户第一时间能看到内容的更新,我们在开发的时候,每次打开网页的时候应该先清理一下缓存。iOS提供了清理的接口。


# 一. 代码实现

在加载 webViewViewControllerviewDidLoad中实现这些代码,可以保证每次加载的webView的内容都是最新的。

	if ([[[UIDevice currentDevice]systemVersion]intValue ] >= 9.0) {
	
        NSArray * types =@[WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeDiskCache]; // 9.0之后才有的
        NSSet *websiteDataTypes = [NSSet setWithArray:types];
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        }];
        
    } else {
    
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSLog(@"%@", cookiesFolderPath);
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
    }