清除WKWebView cookies

来源:互联网 发布:java phantomjs pdf 编辑:程序博客网 时间:2024/05/22 07:40

在UIWebView下,可以使用

[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. [[NSURLCache sharedURLCache] removeAllCachedResponses];//清除缓存  

来实现清除缓存,但当替换使用WKWebView后,这个方法并不生效了(据说WKWebView不支持,我没找到官方说法~)

不过寻找了一下解决方法,分享一下

--------------IOS9以上----------------

[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore];  
  2.     [dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes]  
  3.                      completionHandler:^(NSArray<WKWebsiteDataRecord *> * __nonnull records) {  
  4.                          for (WKWebsiteDataRecord *record  in records)  
  5.                          {  
  6. //                             if ( [record.displayName containsString:@"baidu"]) //取消备注,可以针对某域名清除,否则是全清  
  7. //                             {  
  8.                                  [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes  
  9.                                                                            forDataRecords:@[record]  
  10.                                                                         completionHandler:^{  
  11.                                                                             NSLog(@"Cookies for %@ deleted successfully",record.displayName);  
  12.                                                                         }];  
  13. //                             }  
  14.                          }  
  15.                      }];  

但显然大多小伙伴们都需要支持IOS8的,所以尴尬的是上面的方法暂时用不到,所以还是老老实实的这么干XD

--------------IOS8以上---------------

[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];  
  2. NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];  
  3. NSError *errors;  
  4. [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors]; 
0 0
原创粉丝点击