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