How to archive and unarchive an SKPhysicsBody array using UserDefaults since iOS 12.0

I can successfully archive and unarchive an array of SKPhysicsBody's using UserDefaults as below but the unarchive process has been deprecated. This is the warning message... 'unarchiveObject(with:)' was deprecated in iOS 12.0: Use +unarchivedObjectOfClass:fromData:error: instead. I have been going round and round in circles with this and still not working. How would I conform to this? my code is below.

To archive...

do { try UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject:Sat1shapes,requiringSecureCoding:true), forKey: "Sat1shapes")
 }
catch { 
print(error)}

To unarchive...

var Sat1shapes: [SKPhysicsBody] = []
                
if let dataObject = UserDefaults.standard.value(forKey: "Sat1shapes") as? NSData {
                    Sat1shapes = NSKeyedUnarchiver.unarchiveObject(with: dataObject as Data) as! [SKPhysicsBody]
                    }

Here is the updated code that avoids warning but it is not storing the [SKPhysicsBody] array as with the deprecated version.

var Sat1shapes: [SKPhysicsBody] = []
        
         let dataObject = UserDefaults.standard.value(forKey: "Sat1shapes") as? NSData
        do  {
            Sat1shapes = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSArray.self, SKPhysicsBody.self], from: dataObject! as Data) as! [SKPhysicsBody]
            
            } catch {
                print(error)
            }
   


Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation