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,如果您遇到以下问题,它将帮助您更快地检测: