samwize
samwize

Reputation: 27353

Prevent universal links from opening in `WKWebView`/`UIWebView`

When user tap on a universal link in WKWebView, the corresponding app will be opened (if installed).

This is described in Apple Search Programming Guide

If you instantiate a SFSafariViewController, WKWebView, or UIWebView object to handle a universal link, iOS opens your website in Safari instead of opening your app. However, if the user taps a universal link from within an embedded SFSafariViewController, WKWebView, or UIWebView object, iOS opens your app.

In my app, I have a WKWebView, but I don't want the user to go out of my app. I want to handle the link within my WKWebView.

How do I prevent universal link from opening? Or can I know if a URL could be handle by other apps?

Upvotes: 11

Views: 10101

Answers (4)

Karthik Murugesan
Karthik Murugesan

Reputation: 1120

Can you try this?

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    decisionHandler(WKNavigationActionPolicy(rawValue: WKNavigationActionPolicy.allow.rawValue + 2)!)
}

Upvotes: 1

徐竟峰
徐竟峰

Reputation: 157

Base on @none 's answer, here is an example for Swift 4

I've tested it and it does work!

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    decisionHandler(WKNavigationActionPolicy(rawValue: WKNavigationActionPolicy.allow.rawValue + 2)!)
}

Upvotes: 6

None
None

Reputation: 283

sourcecode for WebKit:

static const WKNavigationActionPolicy WK_API_AVAILABLE(macosx(10.11), ios(9.0)) _WKNavigationActionPolicyAllowWithoutTryingAppLink = (WKNavigationActionPolicy)(WKNavigationActionPolicyAllow + 2);

if you are using WKWebView, just use WKNavigationActionPolicyAllow + 2 instead of WKNavigationActionPolicyAllow

Upvotes: 14

None
None

Reputation: 283

+[LSAppLink openWithURL:completionHandler:] this is how universal link open corresponding app. you can exchange its implementations with yourself method but be carefule,this is private API.

you can check LSAppLink head file here

Upvotes: 2

Related Questions