在Swift中将HTML转换为纯文本

Zai*_*yed 63 uitableview ios swift

我正在开发一个简单的RSS阅读器应用程序作为Xcode中的初学者项目.我目前设置它解析feed,并放置标题,发布日期,描述和内容,并将其显示在WebView中.

我最近决定在用于选择帖子的TableView中显示描述(或内容的截断版本).但是,这样做时:

cell.textLabel?.text = item.title?.uppercaseString
cell.detailTextLabel?.text = item.itemDescription //.itemDescription is a String
Run Code Online (Sandbox Code Playgroud)

它显示了帖子的原始HTML.

我想知道如何将HTML转换为纯文本,仅用于TableView的详细UILabel.

谢谢!

Leo*_*bus 213

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

编辑/更新:

讨论不应从后台线程调用HTML导入程序(即,选项字典包含值为html的documentType).它将尝试与主线程同步,失败和超时.从主线程调用它可以工作(但如果HTML包含对外部资源的引用,仍然可以超时,这应该不惜一切代价避免).HTML导入机制用于实现降价(即文本样式,颜色等),而不是用于常规HTML导入.

Xcode 9•Swift 4

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 ?? ""
    }
}
Run Code Online (Sandbox Code Playgroud)

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 ?? ""
    }
}
Run Code Online (Sandbox Code Playgroud)
cell.detailTextLabel?.text = item.itemDescription.html2String
Run Code Online (Sandbox Code Playgroud)

  • 这种方法非常重要 (8认同)
  • 嗨@LeonardoSavioDabus,它有效,所以感谢提示. (3认同)

Suh*_*til 6

斯威夫特 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
      } 
   }
}
Run Code Online (Sandbox Code Playgroud)