Pankaj Gaikar Pankaj Gaikar - 6 months ago 374
iOS Question

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.

Answer

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