How to set WKWebView cookie accept policy?

Lorenzo Boaro

Update: Starting from iOS 12 this workaround does not work anymore. Apple has removed cookies from response headers. For further information take a look at https://bugs.webkit.org/show_bug.cgi?id=188691.

On a UIWebView is possible to set the cookie accept policy in order to deal with third part cookies through HTTPCookieStorage as follows:

Starting from iOS 8, Apple has deprecated UIWebView in favor of the new powerful WKWebView.

The code above has no effect with the new web view since each WKWebView instance has its own cookie storage represented by WKHTTPCookieStore class. In addition, it seems there is no public API to achieve the desired behavior.

And now what?

WKWebView offers different callbacks provided by WKNavigationDelegate. The one that can be used is func webView(WKWebView, decidePolicyFor: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void).

Every time a response is returned, it’s possible to grab the cookies from the header fields and save them into the cookie store. The solution is the following:

And that’s it!

Note: Even if the solution seems to work, I’m not sure it’s the right approach. setCookie has a completion handler and I guess it performs asynchronously.


If you have any questions or comments, please let’s discuss here!

Lorenzo Boaro

Written by

Software Engineer | Writer & Tech Editor @ Ray Wenderlich | Ph.D. in Computer Science

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade