我有一个几乎完全空的应用程序,主要由一个 WKWebView 组成。
用例基本上是一个浏览器。
单击指向域的链接时,该域有一个自己的应用程序链接到该域并且其应用程序(通过apple-app-site-association链接)安装在设备上,我怎样才能阻止链接被打开应用程序(而不是我的网络视图)?
我尝试实现 WKNavigationDelegate 的方法,但只能完全取消导航。
我想要发生的事情:
取而代之的是:
如果目标是打开同一页面中的任何链接,您可以尝试下一个实现:
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView = WKWebView(frame: view.bounds)
webView.navigationDelegate = self
view.addSubview(webView)
if let url = URL(string: "https://www.example.com") {
webView.load(URLRequest(url: url))
}
}
// MARK: WKNavigationDelegate
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.targetFrame == nil || navigationAction.targetFrame?.isMainFrame == false {
// If the navigation action does not have a target frame or it is not the main frame,
// load the request in the same view by calling `load(_:)` on the WKWebView instance.
webView.load(navigationAction.request)
decisionHandler(.cancel)
} else {
// If the navigation action has a target frame and it is the main frame, allow the navigation to proceed.
decisionHandler(.allow)
}
}
}