15

I am building a hybrid iOS app around WKWebView. When the user taps a link the request is hijacked and a new view controller is pushed on the navigation stack. The new controller creates a new WKWebView and loads the existing request. This enabled the app to "feel" native but have the content rendered on the web.

By use of the Safari debugging tools I've noticed that no assets are being cached between web views. However, if I re-request something in an existing web view all of the JavaScripts and CSS are marked as "cached".

So, is it possible to share the cache between WKWebView instances? They are already sharing the same WKProcessPool to share cookies.

Community
  • 1
  • 1
Joe Masilotti
  • 16,815
  • 6
  • 77
  • 87

1 Answers1

-1

WKWebView has a lot of catching up to. If you've already implemented a shared WKProcessPool, you can try manually fetching and storing the cookies.

Try this:

    func webView( _ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void )
    {
        assert( self.webView == webView )
        decisionHandler( .allow )
        guard let httpResponse = navigationResponse.response as? HTTPURLResponse else { return }
        guard let url = httpResponse.url else { return }
        let cookies = HTTPCookie.cookies( withResponseHeaderFields: httpResponse.allHeaderFields as! [String : String], for: url )
        let _ = cookies.map{ HTTPCookieStorage.shared.setCookie( $0 ) }
    }

Obviously you can decide to allow or reject, that's just an example. WKWebView does not currently share cookies in the standard shared cookie storage location as UIWebView does. This should resolve that for most cases.