开发者

NSDataDetector with NSTextCheckingTypeLink detects URL and PhoneNumbers!

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

The result is that it finds the URL and the number. The number is dete开发者_如何学编程cted as a phone-Number:

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

Is that a bug? Could anyone tell me how to get the URL without that telephone number?


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}.

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.

The better way to check this would be like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜