发布于 4年前
Swift 4转换html为字符串文本
Swift 4可以添加extension来把html转换为字符串。
String添加扩展
extension String {
var html2AttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: Data(utf8),
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
} catch {
print("error: ", error)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
NSAttributedString需要加上选项
.documentType: NSAttributedString.DocumentType.html
使用
let str = htmlData.html2String