我有一个WKWebView,我想要在选择号码时拨打电话号码。 Web视图的内容包含HTML锚标记“tel:”,我正在寻找一种方法来捕获它。哪个函数用于捕获这些标记?
答案 0 :(得分:12)
设置webView的navigationDelegate
属性并实现委托的以下功能( WKNavigationDelegate )
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {
if navigationAction.request.url?.scheme == "tel" {
UIApplication.shared.openURL(navigationAction.request.url!)
decisionHandler(.cancel)
} else {
decisionHandler(.allow)
}
}
自iOS 10起,您还可以在dataDetectorTypes
上将.phoneNumber
设置为WKWebViewConfiguration
。所有检测到的电话号码都将转换为包含电话号码周围的链接,因此上述功能将通过带有" tel"点击电话号码时的方案。
configuration.dataDetectorTypes = .phoneNumber
答案 1 :(得分:1)
已修复使用“decisionPolicyFor navigationAction”委托方法在WKWebView
中拨打电话:
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.request.url?.scheme == "tel" {
UIApplication.shared.openURL(navigationAction.request.url!)
decisionHandler(.cancel)
} else {
decisionHandler(.allow)
}
}
设置Web视图时,请在其配置中设置数据检测器类型:
if #available(iOS 10.0, *) {
webView.configuration.dataDetectorTypes = .phoneNumber
}
答案 2 :(得分:0)
Swift4
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.targetFrame == nil {
webView.load(navigationAction.request)
}
if navigationAction.request.url?.scheme == "tel" {
UIApplication.shared.openURL(navigationAction.request.url!)
decisionHandler(.cancel)
}
else if navigationAction.request.url?.scheme == "mailto" {
UIApplication.shared.openURL(navigationAction.request.url!)
decisionHandler(.cancel)
}
else{
decisionHandler(.allow)
}
}
您也可以see this example供参考。它可以在100%的真实设备上运行