我正在尝试打开与本地html文件的IOS应用程序的外部链接。我正在使用Xcode12.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)
}
}
}发布于 2021-09-06 23:19:50
显然,您的webView(_:decidePolicyFor:decisionHandler:)委托函数永远不会被调用。通过添加断点或打印来检查它。
要解决此问题,只需设置WKWebView的navigationDelegate并符合WKNavigationDelegate
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate { // <- conform to WKNavigationDelegate
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = self // <- set the navigationDelegate property
webView.uiDelegate = self
view = webView
}
}https://stackoverflow.com/questions/69076821
复制相似问题