I'm trying to switch an existing app from UIWebView
to WKWebView
. The current app manages the users login / session outside of the webview
and sets the cookies
required for authentication into the the NSHTTPCookieStore
. Unfortunately new WKWebView
doesn't use the cookies
from the NSHTTPCookieStorage
. Is there another way to achieve this?
Ios – set the cookies to be used by a WKWebView
cookiesiosios8uiwebviewwkwebview
Best Answer
Edit for iOS 11+ only
Use WKHTTPCookieStore:
Since you are pulling them over from HTTPCookeStorage, you can do this:
Old answer for iOS 10 and below
If you require your cookies to be set on the initial load request, you can set them on NSMutableURLRequest. Because cookies are just a specially formatted request header this can be achieved like so:
If you require subsequent AJAX requests on the page to have their cookies set, this can be achieved by simply using WKUserScript to set the values programmatically via javascript at document start like so:
Combining these two techniques should give you enough tools to transfer cookie values from Native App Land to Web View Land. You can find more info on the cookie javascript API on Mozilla's page if you require some more advanced cookies.
Yeah, it sucks that Apple is not supporting many of the niceties of UIWebView. Not sure if they will ever support them, but hopefully they will get on this soon. Hope this helps!