如何存储SKScene,包括应用程序关闭时创建的所有SKSpriteNodes?

时间:2015-08-08 16:10:00

标签: ios swift

这是我的第一个问题,也是Swift的新手,因此对语法或语义的任何缺失感到抱歉;)

我正在使用Swift构建一个iOS应用程序,需要存储一个自己的TablesScene类的状态,该类是关闭应用程序时SKScene的子类,以便在重新打开它时将其恢复。 这个场景由许多ViewControllers中的一个调用,可以通过Tab Bar Controller访问。

我知道NSCoder已经尝试过了......

在AppDelegate中添加了此属性以获取Scene ...

的句柄
var tablesScene: TablesScene?

...我正在填充TablesScene本身,如下所示......

override func didMoveToView(view: SKView) {
        backgroundColor = SKColor.whiteColor()
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appDelegate.tablesScene = self
    }

...然后将此func添加到AppDelegate以获取正确的归档目录...

class func getPrivateDocsDir() -> String {
    let paths = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0].stringByAppendingPathComponent("Private Documents")
    var error:NSError?
    NSFileManager.defaultManager().createDirectoryAtPath(documentsDirectory, withIntermediateDirectories: true, attributes: nil, error: &error)
    return documentsDirectory

}

...然后将其归档场景......

func applicationDidEnterBackground(application: UIApplication) {
    self.saveContext()
    if let view = window?.rootViewController?.view {
        let documentsDirectory = AppDelegate.getPrivateDocsDir()
        let filePath = documentsDirectory.stringByAppendingPathComponent("autosaved-scene")
        let data = NSMutableData()
        let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
        archiver.encodeObject(tablesScene, forKey: "AppDelegateSceneKey")
        archiver.finishEncoding()
        data.writeToFile(filePath, atomically: true)
    }
}

...这是为了检索TablesScene状态......

func applicationDidBecomeActive(application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    if let view = window?.rootViewController?.view  {

        let dataPath = AppDelegate.getPrivateDocsDir().stringByAppendingPathComponent("autosaved-scene")
        if let codedData = NSData(contentsOfFile: dataPath) {
            let unarchiver = NSKeyedUnarchiver( forReadingWithData: codedData)
            let tablesScene = unarchiver.decodeObjectForKey("AppDelegateSceneKey") as? TablesScene
            unarchiver.finishDecoding()
        }

    }
}

...我收到以下信息,但我觉得我的方法有问题。

[NSKeyedUnarchiver initForReadingWithData:]: data is empty; did you forget to send -finishEncoding to the NSKeyedArchiver?

0 个答案:

没有答案