On iOS version lower than 11 the throwing archivedData(withRootObject:requiringSecureCoding:)
is unavailable, so I have tried to do the equivalent on versions less than iOS 11:
let archiveData: NSData
if #available(iOS 11.0, *) {
archiveData = try NSKeyedArchiver.archivedData(
withRootObject: rootObject,
requiringSecureCoding: true
) as NSData
} else {
NSKeyedArchiver.archivedData(withRootObject: userActivity)
let mutableData = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: mutableData)
archiver.requiresSecureCoding = true
archiver.encode(rootObject, forKey: NSKeyedArchiveRootObjectKey)
if let error = archiver.error {
throw error
}
archiver.finishEncoding()
archiveData = mutableData
}
However, when the rootObject
calls NSCoder.failWithError(_:)
in the encode(with:)
function an NSInvalidUnarchiveOperationException
exception is raised.
If I subclass NSKeyedArchiver
as such:
final class KeyedArchiver: NSKeyedArchiver {
override var decodingFailurePolicy: NSCoder.DecodingFailurePolicy {
return .setErrorAndReturn
}
}
It instead raises an NSInternalInconsistencyException
exception with the message Attempting to set decode error on throwing NSCoder
.
Is there a way to do this kind of archiving without throwing an exception, short of writing an Objective-C function to catch the exception and throwing it as an error?
.decodingFailurePolicy
is effective only on decoding (unarchiving viaNSKeyedUnarchiver
), not encoding. What is the error that therootObject
produces, and why? If the error would be detectable up-front, the best way to avoid this would be to not even attempt encoding — otherwise, you're likely going to need to catch the exception in Obj-C.rootObject
will produce an error or not, so I wanted to be as safe as possible on iOS versions prior to 11.0. I was hoping I wouldn't have to use Obj-C but it sounds like I don't have any other choice. Thank you for your comment :)