Reputation: 21
I have cookies stored that i retrieved from a server. Using such cookies, i want to open a webview which logs in the last session as stored by said cookie. How can I inject those cookies
Upvotes: 0
Views: 892
Reputation: 449
I think the quickest way would be to instantiate HTTPCookie and add it to web views configuration. Something like this:
let cookie = HTTPCookie(properties: [...])!
/* Something like this
let cookie = HTTPCookie(properties: [.domain: "something.org",
.path: "/",
.name: "cookieName",
.value: "cookieValue",
.expires: NSDate(timeIntervalSinceNow: 31556926)])!
*/
webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
Upvotes: 1
Reputation: 423
let wkCookieStore = WKWebsiteDataStore.default().httpCookieStore
if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
wkCookieStore.setCookie(cookie) {
}
}
}
I use this method to sync cookies from httpcookiestorage to wkcookiestorage, hopefully as of now you may have understood the wkwebview cookie storage is different and nsurlsession cookie storage is different.
i sync the cookies on
webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!)
This way you won't miss any cookies need to be set to the subsequent requests made by the webpage.
Upvotes: 0