The online home of John Pollard

Fixed an issue using WkWebView when session cookies were intermittently dropped

This bug took about 2 years to fix!

Fingers crossed, but I think I’ve finally fixed an irritating issue in my Yeltzland iOS app, where session cookies were being intermittently dropped in WkWebView.

This was especially painful when using the Yeltz Forum as you’d be logged out of your account every so often 😞.

The problem is (always) threading

I’ve spent ages over the years trying different solutions to see what’s happening, and as far as I can the root cause is that WkWebView actually runs on a different process than the app, which can prevent cookies being synched properly - and hence being dropped if you are unlucky.

The solution

I changed the code to use a single WKProcessPool for all web views in the app, and then instantiate each WkWebView is created using the following code:

lazy var webView: WKWebView = {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    
    // Use a single process pool for all web views
    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.processPool = appDelegate.processPool

    let webView = WKWebView(frame: .zero, 
                    configuration: webConfiguration)
    webView.navigationDelegate = self
    
    return webView
}()

This was based on a very helpful comment by LinhT_24 in the Apple Developer Forums, for which I’ll be eternally grateful.

I’ve been running this code for nearly two weeks now without being logged out from the forum, so I really hope this is fixed.

Hopefully this post might help someone else with the same problems too!