Search code examples
iosswiftnsattributedstring

How to find urls in NSAttributedString?


I have simple attributed string:

let string = NSAttributedString(string: "hello https://www.stackoverflow.com")

When I display that string I would like to see:

hello URL

where URL is clickable link and opens https://www.stackoverflow.com.

The link is not hardcoded, at the time when I replace it, I don't know how much, (if any) links exist there.

EDIT:

Look at the question and compare to the one marked as duplicated. It is NOT DUPLICATED. Please review it wisely and smart.


Solution

  • This should do the trick:

    let linkDetector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
    let str = "hello at https://www.stackoverflow.com or http://google.com ?"
    
    let attrStr = NSMutableAttributedString(string: str)
    
    let matches = linkDetector.matches(in: attrStr.string, range: NSRange(location: 0, length: attrStr.string.utf16.count))
    
    matches.reversed().forEach { aMatch in //Use `reversed()` to avoid range issues
        let linkRange = aMatch.range
        let link = (attrStr.string as NSString).substring(with: linkRange) //Or use Range
        //Here, you could modify the "link", and compute if needed myURLTitle, like URL(string: link)?.host ?? "myURLTitle"
        let replacement = NSAttributedString(string: "myURLTitle", attributes: [.link: link])
        attrStr.replaceCharacters(in: linkRange, with: replacement)
    }
    
    print(attrStr)