Reputation: 1590
I am transitioning an app from UIWebView
to WKWebView
and there's an auto login feature that was handled by saving a cookie with the information that the user was authenticated into NSHTTPCookieStorage
. However WKWebView
does not seem to look at this location for the cookie and therefore the user is prompted with the login screen every time.
Is there something I need to activate to have the WKWebView use cookies properly?
Upvotes: 10
Views: 16465
Reputation: 802
You can read all the cookies from NSHTTPCookieStorage and set these cookies to WKWebview by using WKHTTPCookieStore ( introduced in iOS 11). more about WKWebview : https://developer.apple.com/videos/play/wwdc2017/220/
If you want to support earlier versions, please refer to this answer. Can I set the cookies to be used by a WKWebView?
// get the cookie store (WKHTTPCookieStore) from the webview
let cookieStore =webview.configuration.websiteDataStore.httpCookieStore
//create a cookie
let cookie = HTTPCookie(properties: [ HTTPCookiePropertyKey.domain: "canineschool.org", HTTPCookiePropertyKey.path: "/",HTTPCookiePropertyKey.secure: true,HTTPCookiePropertyKey.name: "ssoToken", HTTPCookiePropertyKey.value: "******"])
// set the cookie to cookieStore
cookieStore.setCookie(cookie!){
//load the request.
}
Important: setCookie is an async request. Completion Handler will be invoked once the cookie is set. https://developer.apple.com/documentation/webkit/wkhttpcookiestore/2882007-setcookie
Upvotes: 2
Reputation: 379
Sharing cookies obtained in native code(using NSURLConnection/NSURlsession) to UIWebview was done by persisting cookies to NSHTTPCookieStorage and UIwebview used these cookies for all the network requests. However there technique doesn't work with WKwebview.
We can however share cookies from native code to WKWebview as following:
While loading the NSURLRequest, we can load cookies as header in the URLRequest and then load the request with WKwebview.
and if you want all the subsequent AJAX calls from WKWebview also to use this cookie, you may want to inject these cookies into the WKWebview while loading the URLRequest.This is explained in detail in the below answer. Can I set the cookies to be used by a WKWebView?
Upvotes: 1
Reputation: 26
let webConfiguration = WKWebViewConfiguration()
webConfiguration.processPool = webProcessPool!
Init each WKWebView
with the WKWebViewConfiguration
, may be surprise for you!
let webview = WKWebView(frame:rect, configuration:webConfiguration)
Upvotes: -5
Reputation: 5065
For now WKWebView and UIWebView does not co-work properly together, due to not sharing of same cookie storage space. It is been discussed in depth in following answer. How can I retrieve a file using WKWebView?
Lets hope Apple fix this in upcomming update.
Upvotes: 7