Group Group Group Group Group Group Group Group Group

Make a URL clickable

#1

Dear All;

I have a string data contains URL inside it. I want to display this data and make the URL clickable to open safari browser. I used different methods for this issue but it keeps the URL only and remove all other data.

Data example:

There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don’t look even slightly believable. http://www.google.com.If you are going to use a passage of Lorem Ipsum, you need to be sure there isn’t anything embarrassing hidden in the middle of text.

Regards
Samer

#2

Hi @samerhameed, I have code that can give you a head start by creating an extension of NSMutableAttributedString. This will allow you to set specific text as a hyperlink with your link.

class ViewController: UIViewController, UITextViewDelegate {
    
    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let linkedText = NSMutableAttributedString(attributedString: textView.attributedText)
        let hyperlinked = linkedText.setAsLink(textToFind: "Terms of use", linkURL: "https://www.google.com/")
        
        if hyperlinked {
            textView.attributedText = NSAttributedString(attributedString: linkedText)
        }
       
    }
}

extension NSMutableAttributedString {
    public func setAsLink(textToFind:String, linkURL:String) -> Bool {
        let foundRange = self.mutableString.range(of: textToFind)
        if foundRange.location != NSNotFound {
            
            self.addAttribute(.link, value: linkURL, range: foundRange)
            
            return true
        }
        return false
    }
}
#3

Dear @gdelarosa,
thank you for your kindly reply and offered solution, but in my case the url is not hard coded and as I understood from your solution you kept the url in hard coded type. So do you have any idea that helps me for my current case.

Samer

#4

Hi @samerhameed,
you need to use regex, where you are parsing the text to look for http/https followed by a :// and then parse it further.

Secondly, what do you want to do, parse URL’s or get data and URL’s both?

cheers,

#5

Hello @jayantvarma,

I found another solution and it saved me. I used textview and enable link detection. it is mush easier.

Thanks a lot

Samer

#6

:+1:t3:

glad you found something that works for you