【问题标题】:Sometime App Crashing NSAttributedString Converting HTML to Attributed String有时应用程序崩溃 NSAttributedString 将 HTML 转换为属性字符串
【发布时间】:2020-04-21 00:19:44
【问题描述】:

将 html 转换为属性字符串时应用程序很少崩溃。

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

【问题讨论】:

  • 发生时有任何崩溃日志吗?
  • 与您的崩溃无关,但如果您从未真正返回 nil 而是返回一个空字符串,则将变量声明为 Optional<NSAttributedString> 是没有意义的。

标签: ios swift nsattributedstring


【解决方案1】:

不应从后台线程调用 HTML 导入器(即 是,选项字典包括 NSDocumentTypeDocumentAttribute 值为 NSHTMLTextDocumentType)。

它会尝试与主线程同步,失败,超时。从主线程调用它是有效的(但如果 HTML 包含对外部资源的引用,仍然会超时,应该不惜一切代价避免这种情况)。 HTML 导入机制旨在实现诸如 markdown 之类的东西(即文本样式、颜色等),而不是用于一般的 HTML 导入。

【讨论】:

    【解决方案2】:

    我在 UIViewRepresentable 中使用 Down 将 markdown 转换为 NSAttributedString 时遇到了类似的问题。

    我的解决方案是将 down.toAttributedString() 调用包装在 DispatchQueue.main.async 块中。

    可能不是最干净的解决方案。但这是我发现唯一有效的方法。

    【讨论】:

      【解决方案3】:

      您首先在空字符串中设置和转换。但是您必须在 onAppear 中使用 DispatchQueue 处理它。之后,您调用之前在代码中创建的变量string,如下所示。

      在您的属性中

      @State private var newTitle : String = ""
      

      如果您使用 SwiftUI,请在下面的代码中添加

      .onAppear{
          DispatchQueue.main.async {
                newTitle = article.title.htmlToAttributedString
            }
       }
      

      【讨论】:

        【解决方案4】:

        试试这个解决方法。 1.像这样创建Data类的扩展。

        1. 以及 String 类的另一个扩展。

          1. 这样调用扩展程序,print("(stringName.html2String)")

        【讨论】:

        • 我的代码和这个有什么区别??除了添加了数据扩展?
        猜你喜欢
        • 2018-02-13
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-15
        • 2021-11-19
        • 1970-01-01
        • 2016-02-20
        相关资源
        最近更新 更多