ios 如何删除 WKWebview cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31289838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete WKWebview cookies
提问by Pankaj Gaikar
For now I am doing like this
现在我正在这样做
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
[storage deleteCookie:cookie];
}
But it is not working on iOS 8, 64-bit device.
但它不适用于 iOS 8、64 位设备。
Any other way the clean cookies of WKWebview? Any help will be appreciated. thanks.
WKWebview的干净cookies还有其他方式吗?任何帮助将不胜感激。谢谢。
回答by Pankaj Gaikar
Apple released new APIs for iOS 9, so now we can remove domain specific cookies stored for WKWebViewwith below code, but this will only work on devices with iOSversion9orlater:
Apple 为iOS 9发布了新的 API ,因此现在我们可以使用以下代码删除为WKWebView存储的域特定 cookie ,但这仅适用于iOS 9或更高版本的设备:
WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore];
[dateStore
fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes]
completionHandler:^(NSArray<WKWebsiteDataRecord *> * __nonnull records) {
for (WKWebsiteDataRecord *record in records) {
if ( [record.displayName containsString:@"facebook"]) {
[[WKWebsiteDataStore defaultDataStore]
removeDataOfTypes:record.dataTypes
forDataRecords:@[record]
completionHandler:^{
NSLog(@"Cookies for %@ deleted successfully",record.displayName);
}
];
}
}
}
];
Above snippet will sure work for iOS 9and later. Unfortunately if we use WKWebViewfor iOS versions before iOS 9, we still have to stick to traditional method and delete the whole cookies storage as below.
以上代码段肯定适用于iOS 9及更高版本。不幸的是,如果我们在iOS 9之前的 iOS 版本中使用WKWebView,我们仍然必须坚持传统方法并删除整个 cookie 存储,如下所示。
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
NSError *errors;
[[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
Below is Swift 3 version
以下是 Swift 3 版本
let dataStore = WKWebsiteDataStore.default()
dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { (records) in
for record in records {
if record.displayName.contains("facebook") {
dataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), for: [record], completionHandler: {
print("Deleted: " + record.displayName);
})
}
}
}
And Swift 4:
和斯威夫特 4:
let dataStore = WKWebsiteDataStore.default()
dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
dataStore.removeData(
ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(),
for: records.filter { let dataStore = WKWebsiteDataStore.default()
dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { (records) in
for record in records {
if record.displayName.contains("facebook") {
dataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), for: [record], completionHandler: {
print("Deleted: " + record.displayName);
})
}
}
}
.displayName.contains("facebook") },
completionHandler: completion
)
}
回答by Simon Epskamp
Swift 3 version of Sarat's answer:
Sarat 答案的 Swift 3 版本:
extension WKWebView {
func cleanAllCookies() {
HTTPCookieStorage.shared.removeCookies(since: Date.distantPast)
print("All cookies deleted")
WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
records.forEach { record in
WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {})
print("Cookie ::: \(record) deleted")
}
}
}
func refreshCookies() {
self.configuration.processPool = WKProcessPool()
}
}
回答by Shubham Mishra
Supports iOS 11.0 and above
支持 iOS 11.0 及以上
Following solution worked well for me:
以下解决方案对我来说效果很好:
Step 1. Remove Cookie from HTTPCookieStorage
步骤 1. 从 HTTPCookieStorage
Step 2. Fetch data records from WKWebsiteDataStore
and delete them.
步骤 2. 从中获取数据记录WKWebsiteDataStore
并删除它们。
Step 3. Create a new WKProcessPool
步骤 3. 创建一个新的 WKProcessPool
Create a WKWebView Extension:
创建一个 WKWebView 扩展:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
webView.cleanAllCookies()
webView.refreshCookies()
}
Usage:
用法:
//// Optional data
NSSet *websiteDataTypes
= [NSSet setWithArray:@[
WKWebsiteDataTypeDiskCache,
//WKWebsiteDataTypeOfflineWebApplicationCache,
WKWebsiteDataTypeMemoryCache,
//WKWebsiteDataTypeLocalStorage,
//WKWebsiteDataTypeCookies,
//WKWebsiteDataTypeSessionStorage,
//WKWebsiteDataTypeIndexedDBDatabases,
//WKWebsiteDataTypeWebSQLDatabases
]];
//// All kinds of data
//NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
//// Date from
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
//// Execute
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
// Done
NSLog(@"remove done");
}];
回答by Kingiol
In iOS9:
在 iOS9 中:
let config = WKWebViewConfiguration()
if #available(iOS 9.0, *) {
config.websiteDataStore = WKWebsiteDataStore.nonPersistentDataStore()
} else {
// I have no idea what to do for iOS 8 yet but this works in 9.
}
let webView = WKWebView(frame: .zero, configuration: config)
回答by Zack Shapiro
None of these options worked for me but I found one that did:
这些选项都不适合我,但我找到了一个:
let dataStore = WKWebsiteDataStore.default()
dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
dataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(),
for: records.filter { extension WKWebView {
private var httpCookieStore: WKHTTPCookieStore { return WKWebsiteDataStore.default().httpCookieStore }
func getCookies(for domain: String? = nil, completion: @escaping ([String : Any])->()) {
var cookieDict = [String : AnyObject]()
httpCookieStore.getAllCookies { cookies in
for cookie in cookies {
if let domain = domain {
if cookie.domain.contains(domain) {
cookieDict[cookie.name] = cookie.properties as AnyObject?
}
} else {
cookieDict[cookie.name] = cookie.properties as AnyObject?
}
}
completion(cookieDict)
}
}
}
.displayName.contains("facebook") },
completionHandler: completion)
}
回答by Subbu
In addition to clearing cookies in the shared cookie storage, i'd try clearing the cache (NSURLCache) and discard the WKWebView and create a new one with a new WKProcessPool
除了清除共享 cookie 存储中的 cookie 之外,我还会尝试清除缓存 (NSURLCache) 并丢弃 WKWebView 并使用新的 WKProcessPool 创建一个新的
回答by Sergi Gracia
Swift 4 and shorter version:
Swift 4 及更短版本:
-(void )getAllCookies
{
NSMutableString *updatedCockies= [[NSMutableString alloc] init];
if (@available(iOS 11.0, *)) {
WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
NSLog(@"cookieStore *********************: %@",cookieStore);
[cookieStore getAllCookies:^(NSArray* cookies) {
NSHTTPCookie *cookie;
for(cookie in cookies){
NSLog(@"%@",cookie)
}
self->updatedCookie = updatedCockies;
NSLog(@"cookie *********************: %@", self->updatedCookie);
}];
}
}
回答by tikamchandrakar
In WKWebView having issue to write and read its taking some time , So when you fetch the cookie some time you will get updated cookie but sometime it will be old one, and you will get error on any server request. I was facing this issue in 3 Days ,
在 WKWebView 中,写入和读取它需要一些时间,因此当您获取 cookie 时,您将获得更新的 cookie,但有时它会是旧的,并且您将在任何服务器请求上出错。我在 3 天内遇到了这个问题,
Solution: No need to store cookies in WKWebsiteDataStore.
解决方案:无需在 WKWebsiteDataStore 中存储 cookie。
Getting cookies:
获取 cookie:
Swift:
迅速:
let config = WKWebViewConfiguration()
if #available(iOS 9.0, *) {
config.websiteDataStore = WKWebsiteDataStore.nonPersistentDataStore()
} else {
// I have no idea what to do for iOS 8 yet but this works in 9.
}
let webView = WKWebView(frame: .zero, configuration: config)
Objective-c :
目标-c:
WKWebViewConfiguration *wkWebConfig = [WKWebViewConfiguration new];
wkWebConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
self.webView = [[WKWebView alloc] initWithFrame: CGRectZero
configuration: wkWebConfig];
Every time you want new cookie so you need to write below code: Given Sharpio
每次您想要新的 cookie 时,您都需要编写以下代码:Given Sharpio
Swift :
斯威夫特:
var libraryPath : String = NSFileManager().URLsForDirectory(.LibraryDirectory, inDomains: .UserDomainMask).first!.path!
libraryPath += "/Cookies"
do {
try NSFileManager.defaultManager().removeItemAtPath(libraryPath)
} catch {
print("error")
}
NSURLCache.sharedURLCache().removeAllCachedResponses()
Objective C--
目标C--
##代码##*******Every time you will get new cookies********
*******每次你都会得到新的饼干********
回答by ykonda
Esqarrouth's answer is only partially right.
The correct swift version is:
Esqarrouth 的回答只是部分正确。
正确的 swift 版本是:
回答by Jeba Moses
WKWebview storing nothing inside [NSHTTPCookieStorage sharedHTTPCookieStorage].
WKWebview 在 [NSHTTPCookieStorage sharedHTTPCookieStorage] 中不存储任何内容。
clearing WKWebsiteDataStorewill be the solution for this problem.
清除WKWebsiteDataStore将是此问题的解决方案。
Still for IOS8 which is using WKwebview, this method is not applicable..
还是对于使用WKwebview的IOS8,这个方法不适用..