szuniverse
szuniverse

Reputation: 1146

Passing Objects To WatchKit with NSKeyedArchiver

class Parent: NSObject, NSCoding {
    var name : String?
    var childs : [Child]?

    override init() {}

    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: "name")
        aCoder.encode(childs, forKey: "childs")
    }

    required init(coder aDecoder: NSCoder) {
        name = aDecoder.decodeObject(forKey: "name") as? String
        childs = aDecoder.decodeObject(forKey: "childs") as? [Child]

        super.init()
    }
}

class Child: NSObject, NSCoding {
    var name: String?

    override init() {}

    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: "name")
    }

    required init(coder aDecoder: NSCoder) {
        name = aDecoder.decodeObject(forKey: "name") as? String
        super.init()
    }
}

// iOS side:

public func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Swift.Void) {

    var parent = Parent()
    parent.name = "John"

    var child1 = Child()
    var child2 = Child()

    parent.childs = [child1, child2]

    NSKeyedArchiver.setClassName("Parent", for: Parent.self)

    let data = NSKeyedArchiver.archivedData(withRootObject: parent)
    replyHandler(["parent": data as AnyObject])

}

// watchOS side:

if WCSession.isSupported() {

    session = WCSession.default()
    session!.sendMessage(["getParent": "getParent"], replyHandler: { (response) -> Void in

        if let rawParent = response as? [String:Data] {

            NSKeyedUnarchiver.setClass(Parent.self, forClassName: "Parent")
            if let parent = NSKeyedUnarchiver.unarchiveObject(with: data) as? Parent {
                // do something
            }

        }
    }, errorHandler: { (error) -> Void in
        print(error)
    })
}

in this case as you can see I used the NSKeyedUnarchiver.setClass and NSKeyedArchiver.setClassName methods which are working but I still get a runtime crash: [NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (Child) for key (NS.objects)

If I remove the NSKeyedUnarchiver.setClass(Parent.self, forClassName: "Parent") and the NSKeyedArchiver.setClassName("Parent", for: Parent.self) rows I get the same error but for Parent class. So I am sure that I have to use the same method call for Child but I dont know where. Anybody has any idea?

Upvotes: 1

Views: 298

Answers (1)

szuniverse
szuniverse

Reputation: 1146

Okey I found the solution, if you have the same structure you just simply set the class names after each other

NSKeyedArchiver.setClassName("Parent", for: Parent.self)
NSKeyedArchiver.setClassName("Child", for: Child.self)

and the same when you unarchive it:

NSKeyedUnarchiver.setClass(Parent.self, forClassName: "Parent")
NSKeyedUnarchiver.setClass(Child.self, forClassName: "Child")

Upvotes: 1

Related Questions