Jose Enrique
Jose Enrique

Reputation: 59

How to scan through a string, identify and convert to NSURL

I would like to go through a string and identify if in that string there is a URL. If there is, I would like to format it in such a way that the user can tap on the URL.

Please note that the strings are not static or always the same. The strings are JSON data that belong to comments and post in an app's feed.

My first idea was to use a regEx expression and create a function that scans through a string, identifies if there is a match for http:// or https://etc. and then turn that range of the string into an NSURL.

Any other ideas, advices, solutions?

Thank you in advance!

Upvotes: 0

Views: 88

Answers (2)

Ronak Chaniyara
Ronak Chaniyara

Reputation: 5435

The NSDataDetector class is a specialized subclass of NSRegularExpression designed to match natural language text for predefined data patterns.

Currently the NSDataDetector class can match dates, addresses, links, phone numbers and transit information.

NSError *error = nil;
   NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink|NSTextCheckingTypePhoneNumber
                                                              error:&error];

Determine the number of matches within a range of a string using the NSRegularExpression method numberOfMatchesInString:options:range:.

NSUInteger numberOfMatches = [detector numberOfMatchesInString:string
                                                          options:0
                                                            range:NSMakeRange(0, [string length])];

Check more at: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSDataDetector_Class/

OR

If you have UITextView or UIWebView you can Detect link by simply setting dataDetectorTypes Property.

For UITextView:

TextView.dataDetectorTypes = UIDataDetectorTypeLink;

For UIWebView:

webView.dataDetectorTypes = UIDataDetectorTypeLink;

For more information check : https://developer.apple.com/library/ios/qa/qa1495/_index.html

Upvotes: 0

Alexander Doloz
Alexander Doloz

Reputation: 4188

Use NSDataDetector. Nice article about it: http://nshipster.com/nsdatadetector/

Upvotes: 1

Related Questions