I have a large code that I try to update to change deprecated APIs.
In the former version, I used forWritingWith and forReadingWith
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
archiver.encode(myObject, forKey: theKey)
if let data = NSMutableData(contentsOf: anURL) {
let unarchiver = NSKeyedUnarchiver(forReadingWith: data as Data)
let myObject = unarchiver.decodeObject(forKey: theKey) as! TheObjectType // <<-- returns the object
That I changed to
let data = NSMutableData()
let archiver = NSKeyedArchiver(requiringSecureCoding: true)
archiver.encode(myObject, forKey: theKey)
if let data = NSMutableData(contentsOf: anURL) {
do {
let unarchiver = try NSKeyedUnarchiver(forReadingFrom: data as Data)
let myObject = unarchiver.decodeObject(forKey: theKey) as? TheObjectType // <<-- This returns nil
This builds correctly.
But on execution, unarchiver.decodeObject now returns nil.
I have searched extensively to find the cause to no avail.
I may probably change the design to avoid NSKeyedArchiver, but that would be a huge refactoring.
I probably miss something obvious.
Could someone hint at the possible cause ?
Hey Claude31, it’s nice for me to be helping you for a change (-:
It’s hard to tell exactly what’s going wrong here without know more about the objects in play. However, in general, when you decode something from a secure keyed archive, you have to tell the system what type you’re expecting. That’s the key factor is what makes it secure.
Over the years I’ve helped a bunch of folks with problems like this. All of these threads have code snippets from me that you should find useful:
- Question about including all project classes in ofClasses parameter when using NSKeyedUnarchiver.unarchivedObject(ofClasses:from:)
- Fragment large size data sent and received using NSKeyedArchiver.archivedData in GameCenter
- Unarchiving an object with custom classes
- XPC, Swift, ObjC, and arrays
- NSKeyedUnarchiver decodeObjectOfClasses failed
- NSKeyedUnarchiver decodeObjectOfClasses failed
- 'unarchiveTopLevelObjectWithData' was deprecated Use unarchivedObject(ofClass:from:) instead
- NSkeyedArchiver fails when trying to archive subclass objects
If you’re still stuck, distill your problem into a test case that I can run, reply here with that, and I’ll take a deeper look.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"