【问题标题】:How to delete WKWebview 's Cache in iOS8?如何在 iOS8 中删除 WKWebview 的缓存?
【发布时间】:2016-07-20 12:07:39
【问题描述】:
【问题讨论】:
标签:
ios
swift
caching
cookies
wkwebview
【解决方案1】:
我正在开发适用于 iOS 的浏览器,并想分享我们在这个问题上的经验。
首先,我们浏览器中的所有 webview 都通过单个 processPool 相互连接。它导致在所有 webView 之间共享 cookie。
为此,我们将相同的 processPool 设置为 WKWebViewConfiguration,将其传递给新创建的 webView:
WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
configuration.processPool = self.processPool;
WKWebView* webView = [[WKWebView alloc] initWithFrame:frame
configuration:configuration];
其次,删除数据的过程是这样的:
删除所有创建的 webView
使用缓存/cookie 删除目录
创建新进程池
使用新进程池重新创建 webViews
如果你有1个webView,整个过程应该是这样的:
- (void)clearWebViewData {
[self.webView removeFromSuperview];
self.webView = nil;
NSFileManager* fileManager = [NSFileManager defaultManager];
NSURL* libraryURL = [fileManager URLForDirectory:NSLibraryDirectory
inDomain:NSUserDomainMask
appropriateForURL:NULL
create:NO
error:NULL];
NSURL* cookiesURL = [libraryURL URLByAppendingPathComponent:@"Cookies"
isDirectory:YES];
[fileManager removeItemAtURL:cookiesURL error:nil];
NSURL* webKitDataURL = [libraryURL URLByAppendingPathComponent:@"WebKit" isDirectory:YES];
NSURL* websiteDataURL = [webKitDataURL URLByAppendingPathComponent:@"WebsiteData" isDirectory:YES];
NSURL* localStorageURL = [websiteDataURL URLByAppendingPathComponent:@"LocalStorage" isDirectory:YES];
NSURL* webSQLStorageURL = [websiteDataURL URLByAppendingPathComponent:@"WebSQL" isDirectory:YES];
NSURL* indexedDBStorageURL = [websiteDataURL URLByAppendingPathComponent:@"IndexedDB" isDirectory:YES];
NSURL* mediaKeyStorageURL = [websiteDataURL URLByAppendingPathComponent:@"MediaKeys" isDirectory:YES];
[fileManager removeItemAtURL:localStorageURL error:nil];
[fileManager removeItemAtURL:webSQLStorageURL error:nil];
[fileManager removeItemAtURL:indexedDBStorageURL error:nil];
[fileManager removeItemAtURL:mediaKeyStorageURL error:nil];
WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
configuration.processPool = [[WKProcessPool alloc] init];
self.webView = [[WKWebView alloc] initWithFrame:frame configuration:configuration];
[self.webView loadRequest:request];
}
我想提请您注意,此代码仅适用于 iOS 8.x 的设备。它在模拟器中根本不起作用。