我将在这里展示一个示例,说明如何在Swift 4中将HTML转换为纯文本。
此示例模拟您收到以下内容:
WordPress&#8216房屋-->WordPress\'House
添加此扩展以将html代码转换为常规字符串:`
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 {
return html2AttributedString?.string ?? ""
}
}
extension String {
var html2AttributedString: NSAttributedString? {
return Data(utf8).html2AttributedString
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
使用扩展名`
let htmlString = "WordPress‘House"
print("String is: ", textFromWP.html2String)