Ios 将属性转换为URL/NSURL

Ios 将属性转换为URL/NSURL,ios,swift,url,nsattributedstring,Ios,Swift,Url,Nsattributedstring,我正在处理一个UITextView,它由NSAttributedString填充 我使用以下代码从属性字符串中提取URL: if let attribute = self.textStorage.attribute(NSAttributedString.Key.link, at: characterIndex, effectiveRange: nil){ let url = URL(string: (attribute as AnyObject).debugDescription ??

我正在处理一个
UITextView
,它由
NSAttributedString
填充

我使用以下代码从属性字符串中提取URL:

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)");
}
获取
URL
似乎不是一种有效的方法,因为我正在将属性转换为它的调试描述,然后使用它来初始化一个新的
URL


是否有更“正式”的方法从属性中获取
URL

我在使用
时从未遇到过问题。将
值链接到
字符串或
URL
,如下所示:

if let urlString = (attribute as? String) ?? (attribute as? URL)?.absoluteString {
    print("URL: \(urlString)")

    // URL from string
    let url = URL(string: urlString)
}

我过去在将
值单独转换为
字符串时遇到了一些问题,我在@RasheshBosamiya的评论中也遇到了这个问题,似乎是
NSAttributedString.Key.link
的值可以是
URL
String
,具体取决于设置的内容/方式。

什么是
属性
类?它不是已经是一个
字符串了吗?那么,如果让attribute=self.textStorage,为什么不做呢。。。作为?字符串
,还是作为?URL`如果它已经是一个
URL
对象。该属性的类型为Any,当我尝试强制转换它时,我会得到一个强制转换错误,即使在print语句的正上方设置断点,也会显示该属性的类型为“NSURL”有没有更有效的方法从键值存储中获取对象?然后
如果let attribute=self.textStorage。。。作为?URL{print(“URL:\(attribute.absoluteString)”;}
不起作用?我建议保存URL,如果您遇到以下问题,它将帮助您更快地检测: