4

In my app, I am loading a page that requires authentication in a WKWebView. On device, it is always authenticated on first load, because I have the proper cookies to authenticate it. However, if I "Erase All Content Settings" on the simulator (under the Hardware menu in the top bar), then the first load of the web view is ALWAYS unauthenticated (even though I have the proper cookies), and the subsequent loads are ALWAYS authenticated.

This does not happen on device, and does not happen when I'm setting break points, meaning that it's some sort of simulator-related race condition.

Here's the code I have for updating cookies from the general cookie storage from my web view.

    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
    }

Is there something I'm doing wrong here? Is this something about my authentication cookies being "HTTPOnly" and WebKit not handling them right? Have other people run into this problem?

Binya Koatz
  • 139
  • 1
  • 6

0 Answers0