Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

This is my situation:

I have a view controller within a WKWebView. This webview starts with a page "A". In this page there are some links (href) and I want that for some of these links must open in the external browser.

For this reason I set the WKWebView delegate:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let url = webView.url?.absoluteString
                if(self.isExternalURL(url))
                    let urlT = URL(string: url)!
                    decisionHandler(.cancel)
                    UIApplication.shared.open(urlT, options: [:], completionHandler: nil)
                    decisionHandler(.allow)
                decisionHandler(.allow)
private func isExternalURL(url:String) -> Bool
    //......check link

My problem is that if I select an external link the external browser opens, but the webview does not remain on page A, but it also loads the external link while I would like it to remain on page A.

I dont know why

Change

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if let url = navigationAction.request.url?.absoluteString
        if self.isExternalURL(url)
            decisionHandler(.cancel)
            UIApplication.shared.open(navigationAction.request.url, options: [:], completionHandler: nil)
            decisionHandler(.allow)
        decisionHandler(.allow)

You can try to use webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!)

func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        if let url = navigationAction.request.url?.absoluteString
            if self.isExternalURL(url)
               webView.stopLoading()
                UIApplication.shared.open(navigationAction.request.url, options: [:], completionHandler: nil)
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.