Search code examples
swiftuiwebview

Swift ShouldStartLoadWith not working when detect url


My application contains Webview To Show Payment Form and when we have done with filling data we can push Done button then Webview will redirect to other Url. I've already searched for this function and I found shouldStartLoadWith function to solve this problem but when I'm implementing this, it's not working

Here is my Code:

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
    }

It's not print either of them.

Here is the rest of my code: I think that i've already called the delegate method of webview but it's still not working

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
    }

Solution

  • Actually, as i seen your webview is using the newer version WKWebview but shouldStartLoadWith function is using for UiWebview instead, For WkWebview is we should using with decisionHandler function. The code should be look like this:

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