NSAttributedString 的初始化使应用程序崩溃

Yaw*_*war 4 ios crashlytics swift swift4

尽管它在do-catch块内,但下面的代码正在崩溃(并非总是但很少)。 Fabric crashlytics指出异常是Fatal Exception: NSInternalInconsistencyException,有时是这样EXC_BAD_ACCESS KERN_PROTECTION_FAILURE 0x000000016fccb1f8

do {
    return try NSAttributedString(
        data: data,
        options: [
            .documentType:  NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ],
        documentAttributes: nil
    )
} catch {
    return NSAttributedString()
}
Run Code Online (Sandbox Code Playgroud)

虽然我阅读了NSAttributedString它的苹果文档,但它指出它应该在主线程上,所以我用Dispatch.main.async块包围它,但这样做并没有设置设置的样式NSAttributedString

Vin*_*eth 6

根据苹果开发者论坛提供的决议:https : //forums.developer.apple.com/thread/115405

遗憾的是,这是 iOS (r. 23592459) 中的一个已知错误,它可能会影响任何从 HTML 构造 NSAttributedString 的人。

除了完全避免使用此 API 之外,没有其他好的解决方法。我的建议:

如果您要显示大量复杂的 HTML,请使用 WKWebView。

如果此 HTML 受到高度限制——也许您只是使用 HTML 作为传输一组受限制的属性(如粗体和斜体)的简单方法——创建您自己的不依赖于 HTML 的标记系统。或者仅解析这些属性的 HTML 并使用结果来创建您的属性字符串。

抱歉,我这里没有更好的消息。

因此,为了避免崩溃,您可能需要避免使用NSAttributedString( data:函数本身并编写自己的方法来解析 html。


Lal*_*hna 4

仅在主线程中更新 UI。

DispatchQueue.main.async {
    textLabel.attributedText = generateAttribString()
}
Run Code Online (Sandbox Code Playgroud)