I am desperately trying to add a custom cookie to a WKWebView
instance (without using Javascript or similar workarounds).
From iOS 11 and upwards, Apple provides an API to do this: The WKWebView
s WKWebsiteDataStore
has a property httpCookieStore
.
Here is my (example) code:
import UIKit
import WebKit
class ViewController: UIViewController {
var webView: WKWebView!
override func viewDidLoad() {
webView = WKWebView()
view.addSubview(webView)
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let cookie = HTTPCookie(properties: [
HTTPCookiePropertyKey.domain : "google.com",
HTTPCookiePropertyKey.path : "/",
HTTPCookiePropertyKey.secure : true,
HTTPCookiePropertyKey.name : "someCookieKey",
HTTPCookiePropertyKey.value : "someCookieValue"])!
let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
cookieStore.setCookie(cookie) {
DispatchQueue.main.async {
self.webView.load(URLRequest(url: URL(string: "https://google.com")!))
}
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
webView.frame = view.bounds
}
}
After this, if I use webView.configuration.websiteDataStore.httpCookieStore.getAllCookies(completionHandler:)
I see that my cookie is in the list of cookies.
However, when inspecting the webview using Safari's developer tools (using a iOS Simulator of course) the cookie does not show up.
I also tried to inspect the traffic using a HTTP proxy (Charles in my case) to see if the cookie in included in my HTTP requests. It is not.
What am I doing wrong here? How can I add a cookie to WKWebView
(on iOS versions 11 and up)?
Any request to
google.com
redirects towww.google.com
.You would need to add
www.
to the domain field of the cookie. If the domain or the path doesn't match the request, the cookie won't be sent.You can add the cookies explicitly.