BlackHatSamurai
BlackHatSamurai

Reputation: 23483

UITextView Not Opening URL When Clicked

I have a UITextView that has an attributed string inside, which contains a URL. The attributed string is being converted to a link, but when you press the link you get an error:

Unknown DDResult category 1 for result ; could not find any actions for URL www.myurl.com

Here is my code:

NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"My Text", nil)];
NSRange range = [str.mutableString rangeOfString:@"www.myurl.com" options:NSCaseInsensitiveSearch];

if (range.location != NSNotFound) {
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"CourierPrime-Bold" size:15] range:NSMakeRange(0, range.location)];
    [str addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"www.myurl.com"] range:range];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor brownColor] range:range];
}


self.welcomeText.editable = NO; 
self.welcomeText.attributedText = str;

//As a note, I have tried this with the value 0 and UIDataDetectorTypeLink
//and neither option worked.
self.welcomeText.dataDetectorTypes = UIDataDetectorTypeAll;

I am using an XIB and in the behavior options I have selectable enabled, and in the detection options I have links selected.

I would like for the link to be opened in the phones mobile browser if possible, rather than creating a webview.

Upvotes: 4

Views: 2789

Answers (2)

SafoineMoncefAmine
SafoineMoncefAmine

Reputation: 165

In Swift :

The URL needs to be Secure (https)

IOS doesn't allow you to redirect the user to non secure links , so provide links with https

and to make a specific string clickable in UITextView using Swift

you can do as follow :

let link = "https://www.google.com"
let range = (text as NSString).range(of: link)
attribute.addAttributes([NSAttributedStringKey.link: link], range: range)

Upvotes: 0

rmaddy
rmaddy

Reputation: 318774

The URL needs a scheme.

This:

[str addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"www.myurl.com"] range:range];

needs to be:

[str addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"http://www.myurl.com"] range:range];

Upvotes: 7

Related Questions