How to call deep links within a WKWebView

When using a web view within the app, if you click on a deep link, it won’t open the deep link and the handlers in the app delegate won’t be invoked. This is expected. In order to fix this, you would need to implement delegate of the WKWebview and then intercept the traffic to handle it separately. This is how you can do it.

class WebViewVC: UIViewController, WKNavigationDelegate {
    var webView: WKWebView!
    var url: URL
    init(url: URL) {
        self.url = url
        super.init(nibName: nil, bundle: nil)
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        webView = WKWebView(frame: view.bounds)
        webView.navigationDelegate = self
        webView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(webView)
        
        webView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.leading.equalTo(view.safeAreaLayoutGuide.snp.leading)
            make.trailing.equalTo(view.safeAreaLayoutGuide.snp.trailing)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
        let request = URLRequest(url: url)
        webView.load(request)
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        guard let url = navigationAction.request.url else {
            decisionHandler(.allow)
            return
        }
        if url.absoluteString == redirectURL {
            handleDeepLink(url)
            decisionHandler(.cancel)
        } else {
            decisionHandler(.allow)
        }
    }

    func handleDeepLink(_ url: URL) {
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
}

In

Leave a Reply

Your email address will not be published. Required fields are marked *