Search code examples
safariswift4wkwebviewxcode10

Using wkWebView to open URL and deeplink but not via safari


This is regarding wkWebview. I want to use wkWebView for my app for the whole operation of browsing internet and when it comes to deep link, I want it to check the apps in phone and open it (if it is available). I know we can use UIApplication.shared.canOpenURL and open method but I think if I use these methods, it will open the safari first and then let the safari do the job for the deep link. I dont want to involve safari at all in this case. So folks, can you please help me? Is there any way that I can exclude safari when I use canOpenURL and Open method?


Solution

  • Set WkWebView Delegate :

     webView.uiDelegate = self
     webView.navigationDelegate = self
    

    Then implement the following method.

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            if navigationAction.navigationType == .linkActivated  {
                if let url = navigationAction.request.url,
                    let host = url.host, !host.hasPrefix("something whatever you want to handle deeplink"),
                    UIApplication.shared.canOpenURL(url) {
                    print(url)
                    print("No need to open it locally")
                    decisionHandler(.cancel)
                } else {
                    print("Open it locally")
                    decisionHandler(.allow)
                }
            } else {
                print("not a user click")
                decisionHandler(.allow)
            }
        }
    

    Do let me know if you have any questions.