I need write and read NSAttributedString
data into a json file, using this previously answered question I can encode the it but it throws an error while decoding.
class AttributedString : Codable {
let attributedString : NSAttributedString
init(attributedString : NSAttributedString) {
self.attributedString = attributedString
}
public required init(from decoder: Decoder) throws {
let singleContainer = try decoder.singleValueContainer()
let base64String = try singleContainer.decode(String.self)
guard let data = Data(base64Encoded: base64String) else { throw DecodingError.dataCorruptedError(in: singleContainer, debugDescription: "String is not a base64 encoded string") }
guard let attributedString = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSAttributedString.self], from: data) as? NSAttributedString else { throw DecodingError.dataCorruptedError(in: singleContainer, debugDescription: "Data is not NSAttributedString") }
self.attributedString = attributedString
}
func encode(to encoder: Encoder) throws {
let data = try NSKeyedArchiver.archivedData(withRootObject: attributedString, requiringSecureCoding: false)
var singleContainer = encoder.singleValueContainer()
try singleContainer.encode(data.base64EncodedString())
}
}
And:
do {
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(attributedString)
let jsonString = String(data: jsonData, encoding: .utf8)
print("***\n\(String(describing: jsonString))\n***") // It works
let jsonDecoder = JSONDecoder()
let attrib = try jsonDecoder.decode(AttributedString.self, from: jsonData)
print(attrib.attributedString.string)
}catch{
print(error) // throws error
}
Error Domain=NSCocoaErrorDomain Code=4864 "value for key 'NS.objects' was of unexpected class 'NSShadow'. Allowed classes are '{( NSGlyphInfo, UIColor, NSDictionary, UIFont, NSURL, NSParagraphStyle, NSString, NSAttributedString, NSArray, NSNumber )}'." UserInfo={NSDebugDescription=value for key 'NS.objects' was of unexpected class 'NSShadow'. Allowed classes are '{( NSGlyphInfo, UIColor, NSDictionary, UIFont, NSURL, NSParagraphStyle, NSString, NSAttributedString, NSArray, NSNumber )}'.}
PS: I need to keep attributes
NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? NSAttributedString
– Leo Dabus