I need to set a cookie in a WKWebView on both iOS 10 an iOS 11. After reading this, I wrote different code for the 2 iOS versions, using a JavaScript script in iOS 10 and WKWebsiteDataStore in iOS 11.
While using iOS 10 I have no issue, with iOS 11 the web app sees the cookie I used in the previous session. I mean, if the first time I launch the app the cookie value is "A", the web app doesn't see the cookie; if I close the app and relaunch it with "B" as the new value of the cookie, the web app now reads "A" from the cookie. However, with the Web Inspector I see the right value of the cookie.
It seems that with the WKWebsiteDataStore the cookie is set too late; how can I solve this issue (without using the same code used in iOS 10 even in iOS 11)?
My code is:
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
let configuration = WKWebViewConfiguration()
let userContentController = WKUserContentController()
configuration.preferences = preferences
if #available(iOS 11, *) {
if let cookie = cookie {
let dataStore = WKWebsiteDataStore.default()
dataStore.httpCookieStore.setCookie(cookie) {
configuration.websiteDataStore = dataStore
configuration.userContentController = userContentController
self.createAndLoadWebView(with: configuration)
}
}
} else {
if let cookie = cookie {
let script = getJSCookiesString(for: [cookie])
let cookieScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false)
userContentController.addUserScript(cookieScript)
configuration.userContentController = userContentController
createAndLoadWebView(with: configuration)
}
}
And then:
private func createAndLoadWebView(with configuration: WKWebViewConfiguration) {
webView = WKWebView(frame: self.containerView.frame, configuration: configuration)
self.containerView.addSubview(webView)
let req = URLRequest(url: pageUrl)
webView.load(req)
}