Search code examples
iosswiftwkwebview

WKWebview popup for PDF close button?


My app is running WKWebview to display a website. When an element is clicked it calls window.open() which is caught and depending on the link a PDF is shown:

func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
    popupWebView = WKWebView(frame: view.bounds, configuration: configuration)
    popupWebView!.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    popupWebView!.navigationDelegate = self
    popupWebView!.uiDelegate = self
    popupWebView!.allowsBackForwardNavigationGestures = true
    
    view.addSubview(popupWebView!)
    return popupWebView!
}

In my case it works perfectly fine.

My problem is now that I can not go back because the PDF was opened in fullscreen. Is it possible to enable navigation controls in this kind of pop-up webview? Or is there any way to control the back behaviour by a "back" swipe? I tried to do it via allowsBackForwardNavigationGestures but it does not seem to work...


Solution

  • I don't think the WKWebView has an easy way add a back button, you will need to add the back button on your view (or navigation controller). I've been able to do it like this:

    Observe the canGoBack property change of the webView instance in order to enable/disable (or hide/show) the back button like this:

    popupWebView.addObserver(self, forKeyPath: #keyPath(WKWebView.canGoBack), options: .new, context: nil)
    

    And on the view controller:

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "canGoBack" {
            if webView.canGoBack {
                // enable the back button
            } else {
                // disable the back button
            }
        }
    }
    

    Finally when the user taps the back button it is only necessary to call:

    popupWebView.goBack()