Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDataDetector with NSTextCheckingTypeLink detects URL and PhoneNumbers!

Tags:

cocoa-touch

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 detected 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?

like image 634
user689081 Avatar asked May 11 '11 14:05

user689081


1 Answers

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);
  }
}
like image 168
Dave DeLong Avatar answered Sep 22 '22 14:09

Dave DeLong