For now I am doing like this
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [
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)
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()
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()
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];
Below is 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);
})
}
}
}
And Swift 4:
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
)
}
Supports iOS 11.0 and above
Following solution worked well for me:
Step 1. Remove Cookie from HTTPCookieStorage
Step 2. Fetch data records from WKWebsiteDataStore
and delete them.
Step 3. Create a new WKProcessPool
Create a WKWebView Extension:
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()
}
}
Usage:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
webView.cleanAllCookies()
webView.refreshCookies()
}
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 ,
Solution: No need to store cookies in WKWebsiteDataStore.
Getting cookies:
Swift:
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)
}
}
}
Objective-c :
-(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);
}];
}
}
Every time you want new cookie so you need to write below code: Given Sharpio
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--
WKWebViewConfiguration *wkWebConfig = [WKWebViewConfiguration new];
wkWebConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
self.webView = [[WKWebView alloc] initWithFrame: CGRectZero
configuration: wkWebConfig];
*******Every time you will get new cookies********