【问题标题】:Convert HTML to Plain Text in Swift在 Swift 中将 HTML 转换为纯文本
【发布时间】:2015-03-23 07:56:55
【问题描述】:

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

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

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

它显示帖子的原始 HTML。

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

谢谢!

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    请使用此代码测试 detailTextLabel:

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

    【讨论】:

    • 嗨@AltimirAntonov,感谢您的回复。 item.itemDescription 是一个字符串——也许我应该早点澄清一下。我应该将其转换为 NSData 吗?
    【解决方案2】:

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

    编辑/更新:

    讨论 HTML 导入器不应该从后台调用 线程(即,选项字典包含带有 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
    

    【讨论】:

    • 这个方法处理器很重
    • +1 for Swift 3:默认情况下,Xcode 通过将NSUTF8StringEncoding 转换为String.Encoding.utf8 将我的代码从Swift 2 移植,但它一直在崩溃。感谢这个答案,我能够通过将.rawValue 附加到Encoding 枚举来修复它。
    • 不能在 swift 4 上编译
    • 这在 ios 10 上运行良好,但在 ios 11 上它对 html 数据做了一些奇怪的事情,比如它忽略了自定义字体的字体粗细。除非明确定义。
    • @LeoDabus 我认为这在 Playgrounds 中有些脆弱。关闭 Xcode 并重新启动解决了我第一次遇到的错误。
    【解决方案3】:

    这是我建议的答案。如果你想放入内部函数,而不是扩展。

    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
    

    【讨论】:

      【解决方案4】:

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

      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

      【讨论】:

        【解决方案5】:

        Swift 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
              } 
           }
        }
        

        【讨论】:

        • 任何字符串都可以转换为 utf8 数据。返回可选是没有意义的。就return Data(utf8)
        • 这里我们要在 NSAttributedString 中转换字符串,为什么只返回 Data(utf8) 会有用?
        • 我的意思是 var utf8data: Data { return Data(utf8) } 并从你的方法中移除保护
        • 顺便说一句 localizedDescription 是多余的。只需print(error)
        【解决方案6】:

        在 swift3 中试试这个解决方案

        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()
        

        【讨论】:

          【解决方案7】:
          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    
          

          【讨论】:

            【解决方案8】:

            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
                }
              }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-04-12
              • 2014-09-08
              • 2023-03-20
              • 2011-07-16
              • 2011-07-05
              • 2018-03-17
              相关资源
              最近更新 更多