WKWebKit:没有dataDetectorTypes参数

17
在UIWebView中,向视图添加UIDataDetectorTypes相当容易:
myUIWebView.dataDetectorTypes = UIDataDetectorTypePhoneNumber;

等等。然而,WKWebView 似乎没有类似的属性。这个 参考提到它已经移动到 myWebKitView.configurationWKWebViewConfiguration 属性中,但是 官方文档 和头文件本身都没有提到 dataDetectorTypes

我目前正在尝试将一个使用 UIWebView 的应用程序迁移到 WKWebView,并且该应用程序目前具有可配置的 UIDataDetectorTypes。那么,是否有任何方法可以使用提供的 API 实现此功能,还是我必须编写自己的代码来解析 HTML?

6个回答

26

实际上,WKWebView 没有 dataDetectorTypes 属性。但是在 iOS 10 中,WKWebViewConfiguration 有这个属性。

尝试以下代码片段。

WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
theConfiguration.dataDetectorTypes = WKDataDetectorTypeNone;

WKWebView *webView = [[WKWebView alloc] initWithFrame:_someFrame configuration:theConfiguration];

这将仅在iOS10及以后版本中起作用。


这段程序相关的内容翻译成中文如下:使用代码获取 WKWebView 工作正常,但是如果直接在 xib 中获取 wkwebview 呢?没有找到任何设置配置的方法。 - Hitarth
@Hitarth,在xib中有数据检测器设置。 - Parag Bafna
@ParagBafna。谢谢,我明白了。 - Hitarth

11
引用的文章已经更新以反映iOS 8 beta之间API的更改。 截至8.0.1,WKWebView上没有dataDetectorTypes属性,并且没有其他可比较的公共API。
在该属性被重新添加到类中之前,您必须使用NSDataDetector自己实现此功能,或者只能使用UIWebView

1
谢谢您的回复。您有关于如何实现这样一个属性的想法吗?我打算使用 evaluateJavaScript:completionHandler: 来获取网页加载时的 HTML,然后将 NSDataDetector 应用于文本,但我不确定这是否是最优方法。 - steve richey
我们需要为此编写一个WKWebView扩展,并在GitHub上发布。 - user3246173
2
在iOS10中,WKWebViewConfiguration具有属性"dataDetectorTypes"。 - arango_86

5
你可以在故事板属性检查器中找到。

Screenshot


3

WKWebView数据探测器可以在WKWebViewConfiguration中设置。Swift版本:

let webViewCofig = WKWebViewConfiguration()
webViewCofig.dataDetectorTypes = [.address]
webView = WKWebView(frame: view.frame, configuration: webViewCofig)

有效选项包括phoneNumber、link、address、calendarEvent、trackingNumber、flightNumber、lookupSuggestion和all。将空的[]传递以设置为none。


1

在iOS10中,WKWebViewConfiguration新增了属性dataDetectorTypes。

选项包括phoneNumber、link、address、calendarEvent、trackingNumber、flightNumber、lookupSuggestion和all。


0
一个简单的解决方案来支持WKWebView中的电话号码检测是通过WKUserScript在JavaScript中应用正则表达式检查器
NSString *jScript = @"document.getElementById(\"main\").innerHTML.replace(/[\+\d]{1}[\d]{2,4}[\s,][\d\s-\\(\\),]{7,}/g, \"<a href=\"tel:\$&\">\$&</a>\")";

WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript];

WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
wkWebConfig.userContentController = wkUController;

wkWebV = [[WKWebView alloc] initWithFrame:self.view.frame configuration:wkWebConfig];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接