有时应用程序崩溃NSAttributedString将HTML转换为属性字符串

时间:2020-01-02 10:11:59

标签: ios swift nsattributedstring

将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()
        }
    }
    ```

4 个答案:

答案 0 :(得分:0)

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

它将尝试与主线程同步,失败并超时。从主线程调用它是可行的(但如果HTML包含对外部资源的引用,仍可能会超时,应该不惜一切代价避免这样做)。 HTML导入机制用于实现诸如markdown之类的东西(即,文本样式,颜色等),而不是用于常规HTML导入。

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

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

在您的属性中

@State private var newTitle : String = ""

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

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

答案 3 :(得分:-2)

尝试解决此问题。 1.像这样创建Data类的扩展。 enter image description here

  1. 和String类的另一个扩展。

    enter image description here

    1. 使用这样的扩展名print(“((stringName.html2String)”))
相关问题