Disable UIWebView for opening links to redirect to apps installed on my iPhone

2.9k Views Asked by At

When I browse some link in my app(in UIWebView), it opens the that link's app installed in my device. How can I restrict it to open external app and load the same URL in my UIWebView.

3

There are 3 best solutions below

2
dduyduong On

You can use func webView(UIWebView, shouldStartLoadWith: URLRequest, navigationType: UIWebViewNavigationType) in UIWebViewDelegate to do that. For example:

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    let urlString = request.url?.absoluteString ?? ""
    if urlString == <your app link on webview> {
        return false
    }

    return true
}

You now just replace <your app link on webview> with your actual link that you don't want web view to navigate to

0
Harman On

Maybe someone will find it useful:

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    if navigationType == .linkClicked, let req = request.urlRequest {
       webView.loadRequest(req)
        return false
    }
    return true
}

Thus, I block the opening of the link in the side application, such as YouTube app, but open it in the UIWebView.

0
CmoiJulien On

If you use WKWebView, UIWebView is deprecated you can do this:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
     if navigationAction.navigationType == .linkActivated {
         if let url = navigationAction.request.url {
             webView.load(URLRequest(url: url))
             decisionHandler(.cancel)
             return
         }
     }
     decisionHandler(.allow)
 }