【发布时间】:2021-11-03 16:16:35
【问题描述】:
我正在尝试使用本地 html 文件从 IOS 应用程序打开外部链接。我使用 Xcode 12.5 和 swift 5+。 我的 ViewController 中的代码很简单,只需打开文件夹 (www) 中的 index.html。 现在的问题是我需要在 iPhone 或 iPad 的 Safari 中打开外部链接 http 或 https,而不是在本地应用程序中。我该如何过滤?感谢您的想法。 到目前为止,这是我的代码 - 已更新:
import UIKit
import WebKit
import PDFKit
class ViewController: UIViewController, WKUIDelegate {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
// let myURL = URL(string:"www/index.html")
// let myRequest = URLRequest(url: myURL!)
// webView.load(myRequest)
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "www")!
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
webView.load(request)
}
// WKWebViewNavigationDelegate
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
// Check for links.
if navigationAction.navigationType == .linkActivated {
// Make sure the URL is set.
guard let url = navigationAction.request.url else {
decisionHandler(.allow)
return
}
// Check for the scheme component.
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
if components?.scheme == "http" || components?.scheme == "https" {
if navigationAction.targetFrame == nil {
UIApplication.shared.open(url)
decisionHandler(.cancel)
} else {
decisionHandler(.allow)
}
// Open the link in the external browser.
UIApplication.shared.open(url)
// Cancel the decisionHandler because we managed the navigationAction.
decisionHandler(.cancel)
} else {
decisionHandler(.allow)
}
}
}
【问题讨论】:
-
我正面临这段代码的崩溃。你也是这种情况吗?崩溃是因为
decisionHandler闭包可能被执行2次,首先是.allow,然后是.cancel参数。如果不需要,请尝试完全删除if navigationAction.targetFrame == nil/else语句。 -
不,它不会崩溃。但我会删除这部分。谢谢你的提示。
-
好的,更新了,但还是有同样的问题,还是直接在WKWebView中打开外部链接,而不是在Safari浏览器中。