Swift3/Swift4 转换Html为纯文本
Swift 3或者Swift 4 添加String扩展,把Html字符串转换为纯文本
Xcode 9 beta • Swift 4
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 ?? ""
}
}
Xcode 8.3 • Swift 3.1
extension 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 ?? ""
}
}
使用方法
str.html2String