I have the code below to copy cookies from the general HTTPCookieStorage
, into my webview's cookie store. After all cookies are copied, I load the webview
let webView = WKWebView(frame: containerView.bounds, configuration: WKWebViewConfiguration())
webView.navigationDelegate = navigationDelegate
containerView.addAndFillSubview(webView)
guard let sharedCookies = HTTPCookieStorage.shared.cookies else {
return
}
// For each cookie in the common store, set it in the WKWebView's store.
for sharedCookie in sharedCookies {
// Add a block to the dispatch group every time a cookie begins to be set in the WKWebView's store.
wkSetCookieDispatchGroup.enter()
webView.configuration.websiteDataStore.httpCookieStore.setCookie(sharedCookie) {
// Release a block from the dispatch group every time a cookie is successfully set in the WKWebView's store.
wkSetCookieDispatchGroup.leave()
}
}
// Wait for all the cookies to be successfully set (all blocks in the wkSetCookieDispatchGroup to be released)
wkSetCookieDispatchGroup.notify(queue: .main) {
// Load url in webView
}
The first time this code runs it works - all cookies are set, setCookie
's completion handlers are called and the dispatch group is notified.
However, after n runs (usually 3 or 4) of closing this web view and opening it, setCookie
's completion handlers STOP returning, usually indefinitely. There is some race condition going on, because if I set break points and hit them every time the web view opens, this issue never occurs. After it occurs once, setting break points sometimes gets it to start working again, and sometimes doesn't do anything.
NOTE: This only happens on device. On simulator, this never occurs.
There's no documentation on when setCookie
's completionHandler should return or not return, and the fact that this is a race condition that usually doesn't happen when you have break points makes it incredibly hard to debug.
Has anyone else experienced this? Any advice? I've tried explicitly setting the WKProcessPool in several places, which didn't work. I tried creating the web view before and after creating the configuration. I've tried a bunch of stuff, but still lost
Not sure if this will fit with your requirements but I was running into the same issue and found that the same cookie store was being used for each WKWebViewConfiguration that I was creating to be used with a different WKWebView.
What I ended up doing since I would need the same cookies for any wk webview instance I would use is created a singleton WKWebViewConfiguration that adds the needed cookies once, sets a WKProcessPool and then returns a copy.
The for each different wk webview I needed would set its custom configuration on the copy but not have to interact with the cookie store.
Seems to be working for me after running into the same issue.