阻止 WKWebView 在外部应用程序中打开链接

问题描述 投票:0回答:1

我有一个几乎完全空的应用程序,主要由一个 WKWebView 组成。

用例基本上是一个浏览器。

单击指向域的链接时,该域有一个自己的应用程序链接到该域并且其应用程序(通过apple-app-site-association链接)安装在设备上,我怎样才能阻止链接被打开应用程序(而不是我的网络视图)?

我尝试实现 WKNavigationDelegate 的方法,但只能完全取消导航。

我想要发生的事情:

  1. 我的应用程序已启动
  2. 网站已加载到我的网络视图中
  3. 用户点击链接https://foo.bar.com/some/path
  4. 页面https://foo.bar.com/some/path在我的webview中打开

取而代之的是:

  1. 我的应用程序已启动
  2. 网站已加载到我的网络视图中
  3. 用户点击链接https://foo.bar.com/some/path
  4. foo.com.bar 的app 被打开而不是我的 webview 中的网站
ios swift wkwebview ios-universal-links
1个回答
0
投票

如果目标是打开同一页面中的任何链接,您可以尝试下一个实现:

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)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.