Find URL in string
November 30, 2015
There are times, when we need to parse some string and extract any URLs we find there. Sounds like a simple task, but becomes quite an interesting task to accomplish. Thankfully we have our hero from the Foundation -
Usage
NSString *sample = @"This is some sample string, that leads to http://arsenkin.com";
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [detector matchesInString:sample options:0 range:NSMakeRange(0, sample.length)];
/* Array contains one url http://arsenkin.com */
This block of code had searched the whole string for URLs it could find. It would also find URLs like
In case you would print out the contents of the
NSLog(@"%@", matches);
/* NSDataSetector[21738:3045506] (
"<NSLinkCheckingResult: 0x100111030>{42, 19}{http://arsenkin.com}"
) */
Getting the actual NSURL
Here is how you would actually create
for (NSTextCheckingResult *match in matches) {
NSRange matchRange = [match range];
if ([match resultType] == NSTextCheckingTypeLink) {
NSURL *url = [match URL];
}
}
Here we are simply checking for the type of
More methods
There are more ways you could work with
The class itself has pretty much what you need for basic day-to-day stuff to get done. I really like using it when I have to quickly get URLs from string and I don't want to create a freaking regular expression line of gibberish.