Wednesday, 26 March 2014

Hyperlinks in iOS App by detecting Links, Phone Number, Address and CalendarEvent in UITextView

In many scenarios we have to detect Links(URLs) and Phone Numbers from given NSString and make it similar to hyperlink in HTML.
Suppose you have a string with multiple url's and you want to make it clickable, so as to be able to open it in Safari browser.

In below code i have taken a string which consists of two url's and i want to make it clickable.
So i take a UITextView "txtViewClickableHyperLink" and assigned the NSString "strText" to it.
Now i have used a magic line to setDataDetector of UITextView, this line has power to recognise my url.
By changing type of DataDetector we can recognise:
UIDataDetectorTypeLink                  - URL (Link)
UIDataDetectorTypePhoneNumber   - Phone Number
UIDataDetectorTypeAddress             - Address
UIDataDetectorTypeCalendarEvent   - Calendar Event
UIDataDetectorTypeAll                      - Detects all types

NSString *strText = [NSString stringWithFormat: @"Hey this is my blog: which is hosted on This is my blog here is share my experiences with all of you. So it can help others as well as me in future. "];
UITextView *txtViewClickableHyperLink = [[UITextView alloc] init];
[txtViewClickableHyperLink setFrame:CGRectMake(X_COORDINATE, Y_COORDINATE, WIDTH, HEIGHT)];
[txtViewClickableHyperLink setEditable:NO];
[txtViewClickableHyperLink setDataDetectorTypes:UIDataDetectorTypeLink];
[txtViewClickableHyperLink setText:strText];
[self.view addSubview:txtViewClickableHyperLink];

Now we can detect url, phone number , address and make it clickable using a UITextView in iPhone App.

Sample Code : HERE

1 comment:

  1. Excellent…Amazing…. I’m satisfied to find so many helpful information here within the put up,for latest php jobs in near me. we want work out extra strategies in this regard, thanks for sharing.