cocoa-touch - NSDataDetector 与 NSTextCheckingTypeLink 检测 URL 和电话号码!

标签 cocoa-touch

我正在尝试从一个简单的 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?

最佳答案

NSDataDetector 必然会将电话号码检测为链接,因为在手机上,您可以像链接一样点击它们以发起电话调用(或点击并按住以发起短信, ETC)。我相信当前的区域设置(即 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);
  }
}

关于cocoa-touch - NSDataDetector 与 NSTextCheckingTypeLink 检测 URL 和电话号码!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5965844/

相关文章:

iphone - 在为其 UIAppearance 设置样式时如何定位特定的 UIView?

objective-c - 使用 popToViewController : animated: 选择 View Controller 的更好方法

objective-c - UILabel 文本被截断

iphone - 优化 Cocoa/Objective-C 搜索

ios - 如果应用程序被杀死,NSURLSessionTask 会发生什么

iphone - UIActionSheet 上破坏性按钮的指南

iphone - 如何检测 UISearchBar/UITextField 的输入暂停?

objective-c - 谷歌应用样式帮助查看

iphone - 在 iPhone TableView 单元格的单元格右侧添加小箭头

iphone - 健全性检查 MKCo整理区域