Search code examples
swiftarkitmultipeer-connectivitymcsession

Can't unarchive custom Object with NSKeyedUnarchiver in AR Multiuser


I'm using MultipeerConnectivity to share SCNNodes position in a multiuser AR session.

When I archive (with NSKeyedArchiver.archivedData(withRootObject: someARNode, requiringSecureCoding: true) )

And unarchive (with if let node = try NSKeyedUnarchiver.unarchivedObject(ofClass:SCNNode.self, from: data) {)
Everything works fine, but now I'm trying to send a custom Object like this:

struct ARUser: Codable {
    var idUser : String
    var position: [Double]
}

When I try to unarchive the object received with the NSKeyedUnarchiver.unarchivedObject it let me error.

if let node = try NSKeyedUnarchiver.unarchivedObject(ofClass:ARUser.self, from: data) {...}

I get the syntax error: Incorrect argument label in call (have 'ofClass:from:', expected 'ofClasses:from:')
But if I change the function as suggested by the compiler:

 if let node = try NSKeyedUnarchiver.unarchivedObject(ofClasses:[ARUser.self], from: data) {..}

I get the next syntax error: Cannot convert value of type 'ARUser.Type' to expected element type 'AnyObject.Type'

So, the question here is, what's the correct way to unarchive custom Objects?


Solution

  • Since here you use Codable

    struct ARUser: Codable {
    

    Then

    do {
       let dataToObject = try JSONDecoder().decode(ARUser.self,from:data)
       let objectToData = try JSONEncoder().encode(dataToObject)
    }
    catch { 
       print(error)
    }
    

    NSKeyedUnarchiver is an old Objective-C stuff