Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

cocoa touch - 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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...