Disable WKWebView for opening links to redirect to apps installed on my iPhone
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
Related videos on Youtube
gal
Updated on June 04, 2022Comments
-
gal almost 2 years
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.
-
saagarjha almost 8 yearsSure. If you implement
WKNavigationDelegate
, the methodwebView(_ webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler decisionHandler: (WKNavigationActionPolicy) -> Void)
should be called whenever a link is clicked. Check thenavigationAction.request.URL
property to make sure it's not Etsy, for example; if it is, cancel the navigation using the decisionHandler and go to the website yourself usingloadRequest()
. Hopefully this will prevent Deep Linking.
-
-
Borzh over 6 yearsThis doesn't work on iOS 9-10... When I click on custom scheme url, decidePolicyForNavigationAction is never called.
-
iphondroid over 5 years@Borzh did you find a solution for iOS 10 ?
-
Borzh over 5 yearsNo I didn't... I remember the web team somehow fixed the bug, but don't know how, really.
-
Mrug over 4 yearsThis is because of Universal App Links using the Apple app site association file. Refer developer.apple.com/library/archive/documentation/General/…
-
exp over 3 yearsThis is part of
WKNavigationDelegate
now