Swift ShouldStartLoadWith 在检测时不工作 url

Swift ShouldStartLoadWith not working when detect url

我的应用程序包含用于显示付款表单的 Webview,当我们完成填写数据后,我们可以按下“完成”按钮,然后 Webview 将重定向到其他 Url。我已经搜索过这个函数,我发现 shouldStartLoadWith 函数可以解决这个问题,但是当我实现这个函数时,它不起作用

这是我的代码:

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        if request.url?.absoluteString == "https://xyzbank.com" {

            print("SUCCESS")
            return false
        }
        print("NOT SUCCESS")
        return true
    }

这两个都不打印。

这是我的其余代码:我想我已经调用了 webview 的委托方法,但它仍然不起作用

override func viewDidLoad() {
        super.viewDidLoad()

        hud.textLabel.text = "Processing..."
        hud.show(in: self.view)
        let mpayment: Payment = params.payment

        mywebview.navigationDelegate = self
        //Showing webview url....


    }

    func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
        print(error.localizedDescription)
    }
    func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("Start to load")
    }
    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
        print("DID FINISH NAVIGATION")
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.hud.textLabel.text = "Success"
        self.hud.detailTextLabel.text = nil
        self.hud.dismiss(animated: true)
    }

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        if request.url?.absoluteString == "https://example.com" {

            print("SUCCESS")
            return false
        }
        print("NOT SUCCESS")
        return true
    }

实际上,正如我所看到的,您的 webview 使用的是较新版本的 WKWebview,但是 shouldStartLoadWith 函数用于 UiWebview,对于 WkWebview,我们应该使用 decisionHandler 函数。 代码应如下所示:

 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping ((WKNavigationActionPolicy) -> Void)) {

    print("webView:\(webView) decidePolicyForNavigationAction:\(navigationAction) decisionHandler:\(decisionHandler)")

    if let url = navigationAction.request.url {
            print(url.absoluteString)
            if url.absoluteString.hasPrefix("https://example.com"){
                print("SUCCESS")
         }
    }

    decisionHandler(.allow)
}