Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

When I'm searching google and click on Etsy.com for exmaple, WKWebView redirect me to Etsy app installed on my iPhone. How can I disable this behavior? I want WKWebView to redirect me to etsy.com mobile website. I'm using swift.

like image 458
gal Avatar asked May 07 '16 09:05

gal


1 Answers

Unfortunately, WKWebView doesn’t send urls with custom schemes back to your app to handle automatically.

If you try this without special handling, it will look like your web view hangs after the user authenticates with the third-party service and you’ll never receive your callback. You could try using a redirect URI with the standard http or https scheme, but then WKWebView would just try to load it, rather than directing it out of the web view to your native app to handle.

In order to handle the redirect, you need to implement decidePolicyForNavigationAction in the WebPolicyDelegate of your WKWebView to detect the custom URL scheme and direct it to your app to be handled:

func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: ((WKNavigationActionPolicy) -> Void)) {
        print("webView:\(webView) decidePolicyForNavigationAction:\(navigationAction) decisionHandler:\(decisionHandler)")

        let app = UIApplication.sharedApplication()
        let url = navigationAction.request.URL
        let myScheme: NSString = "https"
        if (url!.scheme == myScheme) && app.canOpenURL(url!) {
            print("redirect detected..")
            // intercepting redirect, do whatever you want
            app.openURL(url!) // open the original url
            decisionHandler(.Cancel)
            return
        }

        decisionHandler(.Allow)
    }

You can find detailed information here

like image 131
Alessandro Ornano Avatar answered Sep 24 '22 00:09

Alessandro Ornano