您可以添加此扩展名以将您的html代码转换为常规字符串:
编辑/更新:讨论不应从后台线程调用HTML导入程序(即,选项字典包含值为html的documentType)。它将尝试与主线程同步,失败和超时。从主线程调用它可以工作(但如果HTML包含对外部资源的引用,仍然可以超时,这应该不惜一切代价避免)。HTML导入机制用于实现降价(即文本样式,颜色等),而不是用于常规HTML导入。
Xcode 9•Swift 4extension Data {
var html2AttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print("error:", error)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}}extension String {
var html2AttributedString: NSAttributedString? {
return Data(utf8).html2AttributedString }
var html2String: String {
return html2AttributedString?.string ?? ""
}}
Xcode 8.3•Swift 3.1extension String {
var html2AttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: Data(utf8), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print("error:", error)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}}cell.detailTextLabel?.text = item.itemDescription.html2String