NSDataDetector with NSTextCheckingTypeLink Detects URLs and PhoneNumbers!

I am trying to get the url from a simple NSString clause. For this, 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); } } 

As a result, it finds the URL and number. The number is defined as the phone number:

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

This is mistake? Can someone tell me how to get the url without this phone number?

+6
source share
1 answer

NSDataDetector necessarily detects phone numbers as links, because on the phone you can use them as if they were a link to initiate a phone call (or press and hold to start a text message, etc.). I believe that the current language (i.e. NSLocale ) determines whether the string of numbers will look like a phone number or not. For example, in the United States of America at least seven digits will be considered as a phone number, since US numbers have the general form: \d{3}-\d{4} .

Regarding the recognition of telephone communications compared to another link, it is not recommended to check http:// at the beginning of the URL. A simple example is enough: what if it is an https:// link? Then your code breaks.

The best way to check this would be as follows:

 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); } } 
+12
source

Source: https://habr.com/ru/post/887843/


All Articles