Spritekit Scene Archiving

248 views Asked by At

The SpriteKit programming guide contains this useful little tidbit:

Store a game level as an archive of a scene node. This archive includes the scene, all of its descendants in the node tree, and all of their connected physics bodies, joints, and actions.

But it doesn't have any info on where or how to store this archive. This is my current code, though it doesn't work:

    // Save Data
    let fileManager = FileManager.default
    let URL = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
    let path = URL.appendingPathComponent("stage1.dat")

    if NSKeyedArchiver.archiveRootObject(stage1, toFile: path.path) != false {
        print("stage saved")
    }
    else {
        print("save failed")
    }

    // Load Data
    var data = Data()
    do{
        data = try Data(contentsOf: path)
    }
    catch{
        print(error)
    }


    let stage = NSKeyedUnarchiver.unarchiveObject(with: data) as? GameScene

edit: Turns out I don't have permission to write to local domain. oops. I switched it to user domain and now the write is working. However, attempting to unarchive that same file is now throwing an NSException. I added the unarchiving code to the block above.

1

There are 1 answers

0
Zek On BEST ANSWER

I ended up using unarchiveTopLevelObjectWithData instead to generate an error I could catch.

Turns out the NSexception was due to trying to decode an optional using something that's not decode object.

This question pretty much sums it up.