WKWebView canGoForward 总是 return false swift 5

WKWebView canGoForward always return false swift 5

我已经实现了 WKWebView,一切正常。 canGoBack 值已更改,但 canGoForward 始终 return 错误。如果我完全启用强制然后它工作但是当 Any forward url 那里然后我想启用前进按钮。

WKWebView 不包含 webViewDidStartLoadwebViewDidFinishLoad 委托方法,所以我使用 didFinish 方法.它适用于后退按钮,但前进按钮不起作用!我已经检查过 Whosebug not find solution for WKWebview.

下面是我的代码:

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
}

仅提及代码与此问题相关 谢谢!

您可以使用 KVO 观察 canGoBackcanGoForward 的变化:

添加观察员:

  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 观察变化(在此处放置 enabling/disabling 按钮逻辑):

 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)")
            }
        }
    }

启用allowsBackForwardNavigationGestures:

    webView.allowsBackForwardNavigationGestures = true

并且不要忘记删除 deinit 中的观察者。