Make a URL clickable

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

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
    }
}

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

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,

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

:+1:t3:

glad you found something that works for you

This topic was automatically closed after 166 days. New replies are no longer allowed.