How to delete WKWebview cookies

问题内容:

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.

Any other way the clean cookies of WKWebview? Any help will be appreciated. thanks.

问题评论:

答案:

答案1:

Apple released new APIs for iOS 9, so now we can remove domain specific cookies stored for WKWebView with below code, but this will only work on devices with iOS version 9 or later:

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 9 and later. Unfortunately if we use WKWebView for iOS versions before iOS 9, we still have to stick to traditional method and delete the whole cookies storage as below.

NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
NSError *errors;
[[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];

答案评论:

using this approach only returns the domain level, i.e. facebook.com , it tells me there are cookies inside it. but i cannot delete or retrieve individual items. For example a session cookie inside facebook. The old approach would flatten all cookies into a single list. Is this by design or am i missing something. No information ive been able to find. – @pankaj
Have you tried removing record of type WKWebsiteDataTypeSessionStorage?
– Pankaj Gaikar
Jun 30 ’16 at 12:40
Sadly its being used as cookie, debugging in safari shows i have two domains being stored with an amount of other items being used cookies, local storage etc. And under HTTPCookieStore you see a flat list across all domains a list of cookies. This session cookie i want is in there. But not when requesting througuh tis new DataStore. I do however see the Two domain items. so its as through i need to drill down a second level.

答案2:

Swift 3 version of Sarat’s answer:

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);
            })
        }
    }
}

答案评论:

答案3:

In iOS9:

//// 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");
}];

答案评论:

答案4:

None of these options worked for me but I found one that did:

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)

答案评论:

答案5:

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

答案评论:

Well, i’m afraid but this isn’t working too.. I read somewhere that I have to delete local library’s from device too, i’ll be trying that too.
– Pankaj Gaikar
Jul 9 ’15 at 8:39
If you use WKProcessPool trick ( from stackoverflow.com/questions/33156567/… ) to share cookies between multiple WKWebViews, you need to create a new WKProcessPool too like in the answer.

答案6:

It seems like NSHTTPCookieStorage is now being used in iOS 8.2 to correctly clear cookies, as required. I had shipped an app which would run this code prior to opening a WKWebView based login:

NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies])
{
    [storage deleteCookie:cookie];
}

Where earlier than iOS 8.2 the website would auto-login using the saved cookies, it now correctly asks the user to re-login. All this happened without me shipping an update to the app. 🙂

答案评论:

It doesn’t really make sense, your code and mine one are same, Though I tried this code too. Nope, This one too not working for me.
– Pankaj Gaikar
Jul 8 ’15 at 11:02
OK no problem i will wait for your answer
For now, i am clueless, and have no idea what’s happening here, still will try some workaround..
– Pankaj Gaikar
Jul 8 ’15 at 11:12
I find on google but many sites say not give clear cooki

答案7:

Esqarrouth’s answer is only partially right.

The correct swift version is:

var libraryPath : String = NSFileManager().URLsForDirectory(.LibraryDirectory, inDomains: .UserDomainMask).first!.path!
libraryPath += "/Cookies"
do {
    try NSFileManager.defaultManager().removeItemAtPath(libraryPath)
} catch {
    print("error")
}
NSURLCache.sharedURLCache().removeAllCachedResponses()

答案评论:

This is correct.

答案8:

WKWebview storing nothing inside [NSHTTPCookieStorage sharedHTTPCookieStorage].

clearing WKWebsiteDataStore will be the solution for this problem.

Still for IOS8 which is using WKwebview, this method is not applicable..

答案评论:

答案9:

Swift version:

var libraryPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomainMask.UserDomainMask, false).first!
libraryPath += "/Cookies"

do {
  let result = try NSFileManager.defaultManager().removeItemAtPath(libraryPath)
  print(result)
} catch {
  print("error")
}
NSURLCache.sharedURLCache().removeAllCachedResponses()

答案评论:

This always returned an error for me. I passed true for the last parameter in NSSearchPathForDirectoriesInDomains and it works

原文地址:

https://stackoverflow.com/questions/47751971/ios-delete-cookies-but-still-logged-in

添加评论

友情链接:蝴蝶教程