NSDataDetector与NSTextCheckingTypeLink检测URL和PhoneNumbers! [英] NSDataDetector with NSTextCheckingTypeLink detects URL and PhoneNumbers!
问题描述
我想从一个简单的NSString句子中获取一个URL。为此,我在下面的代码中使用NSDataDetector:
I am trying to get an URL from a simple NSString sentence. For that I use NSDataDetector in the following code:
NSString *string = @"This is a sample of a http://abc.com/efg.php?EFAei687e3EsA sentence with a URL within it and a number 097843.";
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
if ([match resultType] == NSTextCheckingTypeLink) {
NSString *matchingString = [match description];
NSLog(@"found URL: %@", matchingString);
}
}
结果是它找到URL和数字。该号码被检测为电话号码:
The result is that it finds the URL and the number. The number is detected as a phone-Number:
found URL: http://abc.com/efg.php?EFAei687e3EsA
found URL: tel:097843
这是一个错误?
推荐答案
NSDataDetector
必须将电话号码检测为链接,因为在电话上,您可以点按它们,如同他们是一个链接,以发起电话呼叫(或点击并按住以启动短信等)。我相信当前语言环境(即 NSLocale
)是什么决定一个数字字符串是否看起来像一个电话号码。例如,在美国,至少需要七位数字才能被识别为电话号码,因为美国的数字是一般形式: \d {3} -\d {4}
。
NSDataDetector
necessarily detects telephone numbers as links because on the phone, you can tap them as if they were a link in order to initiate a phone call (or tap and hold to initiate a text message, etc). I believe that the current locale (ie, NSLocale
) is what determines whether a string of numbers looks like a phone number or not. For example, in the United States, it would take at least seven digits to be recognized as a phone number, since numbers in the US are of the general form: \d{3}-\d{4}
.
对于识别电话链接与另一个链接,检查 http://
。一个简单的例子足够了:如果它是一个 https://
链接?
As for recognizing a telephone link versus another link, it's not a good idea to check for http://
at the beginning of the URL. A simple example suffices: what if it's an https://
link? Then your code breaks.
更好的检查方法是:
NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
NSURL *url = [match URL];
if ([[url scheme] isEqual:@"tel"]) {
NSLog(@"found telephone url: %@", url);
} else {
NSLog(@"found regular url: %@", url);
}
}
这篇关于NSDataDetector与NSTextCheckingTypeLink检测URL和PhoneNumbers!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!