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