在 WKWebView 中抓取并拨打电话号码

Catch and call telephone number in WKWebView

我有一个WKWebView,我想在选择号码时要求拨打号码。 Web 视图的内容包含 HTML 锚标记 "tel:",我正在寻找一种方法来捕获它。哪个函数用于捕获这些标签?

设置webView的navigationDelegate属性并实现delegate的如下功能(WKNavigationDelegate)

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if navigationAction.request.url?.scheme == "tel" {
        UIApplication.shared.open(navigationAction.request.url!)
        decisionHandler(.cancel)
    } else {
        decisionHandler(.allow)
    }
}
    

自 iOS 10 起,您还可以在 WKWebViewConfiguration 上将 dataDetectorTypes 设置为 .phoneNumber。所有检测到的 phone 号码都将转换为包含围绕 phone 号码的链接,因此当点击 phone 数.

configuration.dataDetectorTypes = .phoneNumber

已修复以使用 "decidePolicyFor navigationAction" 委托方法在 WKWebView 中进行 phone 调用:

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
}

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%