自iOS 8之后,WKWebView的高性能使很多开发者逐渐从UIWebView转到WKWebView,从此开启了开发者们对WKWebView又爱又恨的历程,趟过很多坑,我这里就说下清理cookie的坑
- 使用UIWebView时,清理cookie使用NSHTTPCookieStorage单例就行了
//清除cookie
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies]){
[storage deleteCookie:cookie];
}
- 到了WKWebView,因为iOS 8并没有提供管理的API,所以只能通过获取沙盒Cookies路径删除
NSString *libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject;
NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
[[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:nil];
- iOS 9之后,苹果提供了WKWebsiteDataStore相关API
if (@available(iOS 9.0, *)) {
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:[NSSet setWithObjects:WKWebsiteDataTypeCookies, nil] modifiedSince:[NSDate distantPast] completionHandler:^{
}];
}
- 但是各位老铁,如果真的用了上面的代码,会发现,清理cookie变成了概率事件,有时好用有时不好用,所以只能用另一个API
[[WKWebsiteDataStore defaultDataStore] fetchDataRecordsOfTypes:[NSSet setWithObjects:WKWebsiteDataTypeCookies, nil]
completionHandler:^(NSArray<WKWebsiteDataRecord *> * _Nonnull records) {
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:[NSSet setWithObjects:WKWebsiteDataTypeCookies, nil]
forDataRecords:records
completionHandler:^{
}
}];
}];