Prevent universal links from opening in `WKWebView

2020-05-24 04:31发布

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?

4条回答
别忘想泡老子
2楼-- · 2020-05-24 04:56

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)!)
}
查看更多
聊天终结者
3楼-- · 2020-05-24 04:59

+[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

查看更多
叛逆
4楼-- · 2020-05-24 05:01

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

查看更多
我想做一个坏孩纸
5楼-- · 2020-05-24 05:06

Can you try this?

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    decisionHandler(WKNavigationActionPolicy(rawValue: WKNavigationActionPolicy.allow.rawValue + 2)!)
}
查看更多
登录 后发表回答