Block cookies in WKWebview

Is there no easy way to block all cookies in WKWebview? I see there is +[WKWebsiteDataStore nonPersistentDataStore] but cookies still are saved. There is WKHTTPCookieStore prorperty on WKWebsiteDataStore.


I see there is a way to delete cookies one at a time asynchronously, which is kind of annoying if I just want to allow users to block cookies if they want to. As far as I can tell the only way to 'block cookies" would be to do the following:


WKHTTPCookieStore *cookieStore = store.httpCookieStore;
    [cookieStore getAllCookies:^(NSArray<nshttpcookie*>*cookies)
    {
        for (NSHTTPCookie *aCookie in cookies)
        {
            [cookieStore deleteCookie:aCookie completionHandler:^{
                //cookie deleted.
            }];
        }
    }];


Is there no better way?


I could (I guess?) add an WKHTTPCookieStoreObserver and run the above code every time the cookie store changes, which seems pretty ridiculous.

Replies

Well, as far as I can tell, calling -addObserver: method on the httpCookieStore doesn't work.


-(void)viewDidLoad
{     [super viewDidLoad];
     WKWebViewConfiguration *config = webView.configuration;
     WKWebsiteDataStore *dataStore = config.websiteDataStore; 
     WKHTTPCookieStore *cookieStore = dataStore.httpCookieStore;
     [cookieStore addObserver:self];

     //Load the request
     [webView loadRequest:theRequest];
}


//.....This is never called?
-(void)cookiesDidChangeInCookieStore:(WKHTTPCookieStore *)cookieStore
{
     NSLog(@"changed");
}