Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Cocoa touch NSDataDetector与NSTextCheckingTypeLink一起检测URL和电话号码!_Cocoa Touch - Fatal编程技术网

Cocoa touch NSDataDetector与NSTextCheckingTypeLink一起检测URL和电话号码!

Cocoa touch NSDataDetector与NSTextCheckingTypeLink一起检测URL和电话号码!,cocoa-touch,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 dataDetectorWit

我试图从一个简单的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
必然会将电话号码检测为链接,因为在电话上,您可以像点击链接一样点击它们以启动电话呼叫(或点击并按住以启动文本消息等)。我相信当前的语言环境(即,
NSLocale
)决定了一组数字是否像电话号码。例如,在美国,至少需要7位数字才能被识别为电话号码,因为在美国,电话号码的一般形式是:
\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);
  }
}

好的,明白了!为了防止获得电话号码,我检查了前七个字母,如:NSString*httpString=[aString substringWithRange:NSMakeRange(0,7)];如果([httpString IsequalString:@“http://“]){//my coding}这真的很奇怪,因为有另一个名为
NSTextCheckingTypePhoneNumber的NSTextCheckingType专门用于检查电话号码。NSTextCheckingTypeLink检测电话号码的行为真的很奇怪。它只检测5~6位数字,而不检测像888-6666这样的真实电话号码。你知道为什么吗?还是一个已知的虫子?对我来说似乎是个虫子。。。这种行为在iOS7中消失了