0

当我按下任何链接时出现此错误。

传递给 -[webView:decidePolicyForNavigationAction:decisionHandler:] 的完成处理程序被多次调用

该链接在 safari 中打开,但应用程序崩溃。

有什么建议么 ?

import UIKit
import WebKit

class Polering: UIViewController, WKNavigationDelegate {
    // Connect the webView from the StoryBoard.
    @IBOutlet weak var webView: WKWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Get the path of the index.html
        guard let htmlPath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "www") else {
            return
        }
        // Create an URL to load it in the webView.
        let url = URL(fileURLWithPath: htmlPath)
        let request = URLRequest(url: url)
        webView.navigationDelegate = self
        webView.load(request)
    }

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        // Check for links.
        if navigationAction.navigationType == .linkActivated {
            // Make sure the URL is set.
            guard let url = navigationAction.request.url else {
                decisionHandler(.cancel)
                return
            }

            // Check for the scheme component.
            let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
            if components?.scheme == "http" || components?.scheme == "https" {

                if navigationAction.targetFrame == nil {
                    UIApplication.shared.open(url)
                    decisionHandler(.cancel)
                    return
                } else {
                    decisionHandler(.allow)
                }

                // Open the link in the external browser.
                UIApplication.shared.open(url)
                // Cancel the decisionHandler because we managed the navigationAction.
                decisionHandler(.cancel)
                return
            } else {
                decisionHandler(.allow)
            }
        } else {
            decisionHandler(.allow)
        }
    }
}
4

1 回答 1

0

因为decisionHandler被调用了2次。它必须被调用一次。

if navigationAction.targetFrame == nil {
    UIApplication.shared.open(url)
    decisionHandler(.cancel)
    return
} else {
    // =======> First time here
    decisionHandler(.allow)
}

// Open the link in the external browser.
UIApplication.shared.open(url)
// Cancel the decisionHandler because we managed the navigationAction.
// =======> Second time here
decisionHandler(.cancel)

您可以修改逻辑修复重复调用到decisionHandler.

如果逻辑正确,只需decisionHandler在 else 部分注释该行。

if navigationAction.targetFrame == nil {
    UIApplication.shared.open(url)
    decisionHandler(.cancel)
    return
}

UIApplication.shared.open(url)
decisionHandler(.cancel)
于 2021-12-16T12:57:33.250 回答