将 NSAttributedString 转换为 html 时检测到错误的 NSStringEncoding 值 0x8000100

问题描述

我在 XCode 的调试器中收到警告:将 NSAttributedString 转换为 html 数据时检测到错误nsstringencoding 值 0x8000100。不知道是什么导致了这个或如何解决它。这是我的代码

let testString = NSAttributedString(string: "test")
    let documentAttributes: [NSAttributedString.DocumentAttributeKey: Any] = [.documentType: NSAttributedString.DocumentType.html]
    let htmlData = try? testString.data(from: NSRange(location: 0,length: testString.length),documentAttributes: documentAttributes)

确实创建了数据,但不确定为什么会收到警告。

解决方法

我终于弄清楚是什么导致了这种情况。似乎 string to data 函数想要了解使用什么文本编码。这是删除调试器警告的固定代码:

let testString = NSAttributedString(string: "test")
    let documentAttributes: [NSAttributedString.DocumentAttributeKey: Any] = [.documentType: NSAttributedString.DocumentType.html,.characterEncoding:String.Encoding.utf8.rawValue]
    let htmlData = try? testString.data(from: NSRange(location: 0,length: testString.length),documentAttributes: documentAttributes)