I archive an NSAttributedString
, which contains an image with NSTextAttachment
on iOS14 and noticed, that unarchiving it on iOS13 fail. On iOS14 the unarchive is successful.
The error logged is this:
Error decoding string object. error=Error Domain=NSCocoaErrorDomain Code=4864
"value for key 'NS.objects' was of unexpected class 'NSTextAttachment'. Allowed classes are '{(
NSGlyphInfo,
UIColor,
NSURL,
UIFont,
NSParagraphStyle,
NSString,
NSAttributedString,
NSArray,
NSNumber,
NSDictionary
)}'." UserInfo={NSDebugDescription=value for key 'NS.objects' was of unexpected class 'NSTextAttachment'. Allowed classes are '{(
NSGlyphInfo,
UIColor,
NSURL,
UIFont,
NSParagraphStyle,
NSString,
NSAttributedString,
NSArray,
NSNumber,
NSDictionary
)}'.}
Is there an option to make that work, or am I doomed here?
This is how the image is inserted into an NSMutableAttributedString
using NSTextAttachment
:
// Add an image:
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = image;
NSMutableAttributedString *strWithImage = [[NSAttributedString attributedStringWithAttachment:textAttachment] mutableCopy];
[s appendAttributedString:strWithImage];
This is the archiving line:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:str requiringSecureCoding:YES error:&error];
This is the unarchiving line, which returns an NSError
instance:
NSError *error = nil;
NSAttributedString *str = [NSKeyedUnarchiver unarchivedObjectOfClass:NSAttributedString.class fromData:data error:&error];
I create the NSData
instance on iOS14, store it to a file and read it in iOS13. This is when it fails.
The error clearly says that
NSTextAttachment
can not be decoded becuase it is not in the list of classes those are supported.You have to find a workaround to make it work on iOS 13 or lower.
POSSIBLE SOLUTION
NSMutableAttributedString
instance.archive
it the same way that you are doing today.[TextAttachmentInfo]
JSON data paired with above data.unarchive
it the same way that you are doing today.[TextAttachmentInfo]
.NSTextAttachment
s into the unarchivedNSMutableAttributedString
instanceHere's some helper code that needs to be tuned and tested further according to your own use case.