Search code examples
iosswiftwebviewwkwebviewswift5

WKWebView canGoForward always return false swift 5


I have implemented WKWebView everything works perfect. canGoBack value changed but canGoForward always return false. If I enable force fully then it works but When Any forward url there then I want to enable forward button.

WKWebView doesn't contain webViewDidStartLoad and webViewDidFinishLoad delegate method so I use didFinish method. It work for back button but forward button not working! I already checked StackOverFlow not find solution for WKWebview.

Below is my code:

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void){
        buttonConfiguration(webView: webView)
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        buttonConfiguration(webView: webView)
}

func buttonConfiguration(webView: WKWebView){
        print("Back", webView.canGoBack)
        print("Forward", webView.canGoForward)
        backButton.isEnabled = webView.canGoBack
        forwardButton.isEnabled = webView.canGoForward
}

Only mention code is related to this question Thank You!


Solution

  • You can observe the changes in canGoBack and canGoForward using KVO:

    Adding Observer:

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

    KVO Observing Changes (Put enabling/disabling button logic here):

     override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            if let _ = object as? WKWebView {
                if keyPath == #keyPath(WKWebView.canGoBack) {
                    print("canGoBack: \(self.webView.canGoBack)")
                } else if keyPath == #keyPath(WKWebView.canGoForward) {
                    print("canGoForward: \(self.webView.canGoForward)")
                }
            }
        }
    

    Enable allowsBackForwardNavigationGestures:

        webView.allowsBackForwardNavigationGestures = true
    

    And don't forget to remove the observer in deinit.