【问题标题】:NSDataDetector with NSTextCheckingTypeLink detects URL and PhoneNumbers!带有 NSTextCheckingTypeLink 的 NSDataDetector 检测 URL 和电话号码!
【发布时间】:2011-05-12 04:45:27
【问题描述】:

我试图从一个简单的 NSString 语句中获取一个 URL。为此,我在以下代码中使用 NSDataDetector:

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 和数字。该号码被检测为电话号码:

found URL: http://abc.com/efg.php?EFAei687e3EsA
found URL: tel:097843

这是一个错误吗?谁能告诉我如何在没有电话号码的情况下获取 URL?

【问题讨论】:

  • 好的,知道了!为了防止获取电话号码,我正在检查前七个字母,例如: NSString *httpString = [aString substringWithRange:NSMakeRange(0,7)]; if ([httpString isEqualToString:@"http://"]) { // 我的编码 }
  • 这真的很奇怪,因为还有另一个名为NSTextCheckingTypePhoneNumber 的 NSTextCheckingType 专门用于检查电话号码。

标签: cocoa-touch


【解决方案1】:

NSDataDetector 必须将电话号码检测为链接,因为在手机上,您可以像点击链接一样点击它们以发起电话呼叫(或点击并按住以发起短信等)。我相信当前的语言环境(即NSLocale)决定了一串数字是否看起来像电话号码。例如,在美国,至少需要七位数字才能被识别为电话号码,因为美国的数字是一般形式:\d{3}-\d{4}

至于识别电话链接与另一个链接,在 URL 的开头检查 http:// 不是一个好主意。一个简单的例子就足够了:如果它是一个https:// 链接呢?然后你的代码就会中断。

更好的检查方法如下:

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);
  }
}

【讨论】:

  • NSTextCheckingTypeLink 检测电话号码的行为真的很奇怪。它只检测 5~6 位数字,而不是像 888-6666 这样的真实电话号码。你知道为什么吗?或者它是一个已知的错误?
  • 对我来说似乎是一个错误......这种行为在 iOS7 中消失了
猜你喜欢
  • 2013-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
  • 1970-01-01
  • 2011-05-30
相关资源
最近更新 更多