The line containing the var sceneData code gives an error, apparently because of the "path" string. Does anyone know how this can be fixed? Thanks!
extension SKNode {
class func unarchiveFromFile(_ file : String) -> SKNode? {
if let path = Bundle.main.path(forResource: file, ofType: "sks") {
var sceneData = Data(bytesNoCopy: path, count: .DataReadingMappedIfSafe, deallocator: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
Data(bytesNoCopy:
expects a pointer rather than a string path.
The API to read Data
from disk is Data(contentsOf
, however that expects an URL
extension SKNode {
class func unarchiveFromFile(_ file : String) -> SKNode? {
if let url = Bundle.main.url(forResource: file, withExtension: "sks") {
do {
var sceneData = try Data(contentsOf: url)
var archiver = NSKeyedUnarchiver(forReadingWith: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} catch {
return nil
}
} else {
return nil
}
}
}
In Swift 3 I'd rename the method to
class func unarchive(from file : String) -> SKNode? { ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With