1

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?

Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90
Jake Chasan
  • 6,290
  • 9
  • 44
  • 90
  • What is `attribute` class? Isn't it already a `String`? So why, no doing, if let attribute = self.textStorage... as? String`, or `as? URL` if it's already an `URL` object. – Larme Jan 28 '19 at 09:06
  • The attribute is of type Any, when I attempt to cast it I get a cast error even thought setting a breakpoint just above the print statement reveals the attribute is of type “NSURL.” Is there a more effective way to get the object from the key value store? – Jake Chasan Jan 28 '19 at 09:10
  • Then `if let attribute = self.textStorage... as? URL{ print("URL: \(attribute.absoluteString)"); }` doesn't work? – Larme Jan 28 '19 at 09:13

1 Answers1

1

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.

AamirR
  • 11,672
  • 4
  • 59
  • 73
  • I'll recommend to save URL, it should help you detect quicker if you can have an issue with this: https://stackoverflow.com/a/48156375/1801544 – Larme Jan 29 '19 at 11:46