虽然上述一些解决方案在某种程度上起到了作用,但问题在于所有链接都开始在外部打开,而不仅仅是那些未遵循HTTPs URL方案的链接,比如mailto、blank、deeplinks等。
我实现了这些WKNavigationDelegate
函数:
decidePolicyFor navigationAction
(文档链接),允许处理甚至不遵循HTTPs方案的URL
使用此导航失败委托函数webView didFailProvisionalNavigation
并检查iOS是否能够处理在新标签页中打开、邮件、深度链接等,因此在您的情况下,它将打开应用商店
您还可以在此WKNavigationDelegate函数中实现与第2点相同的逻辑,以防万一
以下是代码:
class ViewController: UIViewController, WKNavigationDelegate
{
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
let html = """
<a href="https://apps.apple.com/us/app/directorio-notarios-cdmx/id1544000342"> App store Deep link usually doesn't open </a></span></span><br />
<a href="https://landercorp.mx" rel="noopener"> Normal link </a></span></span><br />
"""
let webview = WKWebView()
webview.frame = view.bounds
webview.navigationDelegate = self
view.addSubview(webview)
webview.loadHTMLString(html, baseURL: nil)
}
func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
{
decisionHandler(.allow)
}
func webView(_ webView: WKWebView,
didFailProvisionalNavigation navigation: WKNavigation!,
withError error: Error)
{
manageFailedNavigation(webView,
didFail: navigation,
withError: error)
}
func webView(_ webView: WKWebView,
didFail navigation: WKNavigation!,
withError error: Error)
{
manageFailedNavigation(webView,
didFail: navigation,
withError: error)
}
private func manageFailedNavigation(_ webView: WKWebView,
didFail navigation: WKNavigation!,
withError error: Error)
{
if error.localizedDescription
== "Redirection to URL with a scheme that is not HTTP(S)"
{
let nsError = error as NSError
if let failedURL = nsError.userInfo["NSErrorFailingURLKey"] as? URL
{
if UIApplication.shared.canOpenURL(failedURL)
{
UIApplication.shared.open(failedURL, options: [:],
completionHandler: nil)
}
}
}
}
}
这样就可以处理遵循HTTPs URL方案和不遵循的两种情况。
![Open WKWebview target="_blank" mailto deeplink new tab app store link](https://istack.dev59.com/7y574.gif)
self.webView.UIDelegate = self
在 iOS 10 中起作用,你的 ViewController 需要继承WKUIDelegate
。即class ViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate
。 - ltrainprcreateWebViewWith configuration: WKWebViewConfiguration
没有被调用。我没有loadView
函数,但我已经在viewDidLoad
函数中添加了self.webView.uiDelegate = self
。我错过了什么? - ltrainprwindow.open(url, "_blank")
。你试过了吗? - Crashalot