在 Swift 中将 HTML 转换为纯文本

我正在 Xcode 开发一个简单的 RSS 阅读器应用程序,作为一个初学者项目。目前我已经设置好了,它可以解析提要,放置标题、发布日期、描述和内容,并在 WebView 中显示它。

我最近决定在用于选择文章的 TableView 中显示描述(或内容的截断版本)。不过,在这样做时:

cell.textLabel?.text = item.title?.uppercaseString
cell.detailTextLabel?.text = item.itemDescription //.itemDescription is a String

它显示了文章的原始 HTML。

我想知道如何将 HTML 转换成纯文本,只用于 TableView 的详细 UILabel。

谢谢!

76186 次浏览

请使用以下代码测试 detailTextLabel:

var attrStr = NSAttributedString(
data: item.itemDescription.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true),
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil,
error: nil)
cell.detailTextLabel?.text = attrStr

您可以添加这个扩展以将 html 代码转换为常规字符串:

编辑/更新:

不应从后台调用 HTML 导入程序 线程(即选项字典包括具有 它将尝试与主线程同步,如果失败, 从主线程调用它可以工作(但仍然可以 如果 HTML 包含对外部资源的引用,则超时 应该不惜一切代价避免) 用于实现诸如标记(即文本样式)之类的东西, 颜色等) ,不适用于一般的 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

这里是我建议的答案。如果你想把函数放在内部,就不要用扩展。

func decodeString(encodedString:String) -> NSAttributedString?
{
let encodedData = encodedString.dataUsingEncoding(NSUTF8StringEncoding)!
do {
return try NSAttributedString(data: encodedData, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}

并调用该函数并将 NSAttributedString 强制转换为 String

let attributedString = self.decodeString(encodedString)
let message = attributedString.string

我使用了 Danboz answer,只是将其更改为返回一个简单的 String (而不是一个富文本字符串) :

static func htmlToText(encodedString:String) -> String?
{
let encodedData = encodedString.dataUsingEncoding(NSUTF8StringEncoding)!
do
{
return try NSAttributedString(data: encodedData, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil).string
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}

对我来说,它像魔法一样有效,谢谢 Danboz

斯威夫特4号 Xcode 9

extension String {
    

var utfData: Data {
return Data(utf8)
}
    

var attributedHtmlString: NSAttributedString? {
        

do {
return try NSAttributedString(data: utfData, options: [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
],
documentAttributes: nil)
} catch {
print("Error:", error)
return nil
}
}
}


extension UILabel {
func setAttributedHtmlText(_ html: String) {
if let attributedText = html.attributedHtmlString {
self.attributedText = attributedText
}
}
}

在 Swift 中尝试这个解决方案3

extension String{
func convertHtml() -> NSAttributedString{
guard let data = data(using: .utf8) else { return NSAttributedString() }
do{
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
}catch{
return NSAttributedString()
}
}
}

使用

self.lblValDesc.attributedText = str_postdescription.convertHtml()
let content = givenString // html included string
let attrStr = try! NSAttributedString(data: content.data(using: String.Encoding.unicode, allowLossyConversion: true)!,options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],documentAttributes: nil)
self.labelName.attributedText = attrStr

Swift4.0扩展

 extension String {
var html2AttributedString: String? {
guard let data = data(using: .utf8) else { return nil }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil).string


} catch let error as NSError {
print(error.localizedDescription)
return  nil
}
}
}