Search code examples
iosswifturlnsattributedstring

Convert attribute to URL / NSURL


I am working on a UITextView that is populated by a NSAttributedString.

I use the following code to extract the URL out of the attributed string:

if let attribute = self.textStorage.attribute(NSAttributedString.Key.link, at: characterIndex, effectiveRange: nil){
    let url = URL(string: (attribute as AnyObject).debugDescription ?? "");
    print("URL: \(url.absoluteString)");
}

It does not seem like an efficient way to get the URL, because I am converting the attribute to its debug description, then using that to initialize a new URL.

Is there a more "official" way to get the URL from the attribute?


Solution

  • I never had a issue when casting .link value to either String or URL, like so:

    if let urlString = (attribute as? String) ?? (attribute as? URL)?.absoluteString {
        print("URL: \(urlString)")
    
        // URL from string
        let url = URL(string: urlString)
    }
    

    I faced some issues in the past when casting .link value alone to String, here in my post @RasheshBosamiya in comments also faced this issue, and seems the value of NSAttributedString.Key.link can either be URL or String depending on what/how it is set.