SoFunction
Updated on 2025-04-09

How to clear WKWebView cookies

Under UIWebView, you can use

[[NSURLCache sharedURLCache] removeAllCachedResponses];//Clear cache

How to clear cookies by WKWebView (iOS9 or above)

WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore]; 
  [dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes] 
           completionHandler:^(NSArray<WKWebsiteDataRecord *> * __nonnull records) { 
             for (WKWebsiteDataRecord *record in records) 
             { 
// if ( [ containsString:@"baidu"]) // Cancel the notes, you can clear a domain name, otherwise it will be cleared//               { 
                 [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes: 
                                      forDataRecords:@[record] 
                                    completionHandler:^{ 
                                      NSLog(@"Cookies for %@ deleted successfully",); 
                                    }]; 
//               } 
             } 
           }]; 

This method is used in iOS9:

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

View cookies

NSHTTPCookie *cookie;
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [cookieJar cookies]) {
  NSLog(@"%@", cookie);
}

The above method to clear WKWebView cookies is all the content I share with you. I hope you can give you a reference and I hope you can support me more.