问题是什么?
目前,我正在构建一个应用程序扩展,它通过 JSON 与我的主应用程序通信。主题和数据位于 JSON 中,并通过 Apple 的可编码协议进行解析。我现在遇到的问题是使 NSAttributedString 可编码兼容。我知道它不是内置的,但我知道它可以转换为数据,然后再转换回 nsattributedstring。
到目前为止我有什么?
将 NSAttributedString 转换为数据以便通过 JSON 共享。
if let attributedText = something.attributedText {
do {
let htmlData = try attributedText.data(from: NSRange(location: 0, length: attributedText.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType])
let htmlString = String(data: htmlData, encoding: .utf8) ?? ""
} catch {
print(error)
}
}
将一个HTML格式的JSON字符串转换为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
}
我的问题?
如何创建一个具有属性nsAttributedTitle的结构,该属性是NSAttributedString类型,并使其符合自定义编码器解码器的可编码规范?
结构示例(不考虑可编码合规性):
struct attributedTitle: Codable {
var title: NSAttributedString
enum CodingKeys: String, CodingKey {
case title
}
public func encode(to encoder: Encoder) throws {}
public init(from decoder: Decoder) throws {}
}
required
。 - vadianData
符合Encodable&Decodable
。不需要自己对其进行base64编码。https://stackoverflow.com/questions/58976895/conforming-nsattributedstring-to-codable-throws-error/58978478#58978478 - Leo Dabuspublic required init(from decoder: Decoder) throws { let singleContainer = try decoder.singleValueContainer() guard let attributedString = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(singleContainer.decode(Data.self)) as? NSAttributedString else { throw DecodingError.dataCorruptedError(in: singleContainer, debugDescription: "Data is corrupted") } self.attributedString = attributedString }
- Leo Dabusfunc encode(to encoder: Encoder) throws { var singleContainer = encoder.singleValueContainer() try singleContainer.encode(NSKeyedArchiver.archivedData(withRootObject: attributedString, requiringSecureCoding: false)) }
- Leo Dabus