iosxcodeuiwebviewwkwebviewwkwebviewconfiguration

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.


Solution

  • Apple released new APIs for iOS 9 and newer versions, so now we can remove domain-specific cookies stored for WKWebView with the below code.

    Swift 4/5 version:

    let dataStore = WKWebsiteDataStore.default()
    dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
      dataStore.removeData(
        ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(),
        for: records.filter { $0.displayName.contains("facebook") },
        completionHandler: completion
      )
    }
    

    Below is the Swift 3 version

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

    Objective-C version -

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

    The above snippet will surely work for iOS 9 and later. Unfortunately, if we use WKWebView for iOS versions before iOS 9, we still have to stick to the 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];