您可以添加此扩展名以将html代码转换为常规字符串:
编辑/更新:
讨论不应从后台线程调用HTML导入器(即,选项字典包含值为html的documentType)。它将尝试与主线程同步,失败并超时。从主线程调用它是可行的(但如果HTML包含对外部资源的引用,仍可能会超时,应该不惜一切代价避免这样做)。HTML导入机制旨在实现诸如markdown之类的东西(即,文本样式,颜色等),而不是用于常规HTML导入。
Xcode 11.4•Swift 5.2
extension 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 { html2AttributedString?.string ?? "" }
}
extension StringProtocol {
var html2AttributedString: NSAttributedString? {
Data(utf8).html2AttributedString
}
var html2String: String {
html2AttributedString?.string ?? ""
}
}
cell.detailTextLabel?.text = item.itemDescription.html2String