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
}
}
Then where you have your textView defined, you copy the text to a NSMutableAttributedString, use the setAsLink method on it, which returns true if successful, and use that to copy the linked text back to the textView:
let linkedText = NSMutableAttributedString(attributedString: myTextView.attributedText)
let hyperlinked = linkedText.setAsLink(textToFind: "this part of the text will be hyperlinked", linkURL: "https://www.website.com/")
if hyperlinked {
myTextView.attributedText = NSAttributedString(attributedString: linkedText)
}