class func unarchiveFromFile(file : NSString) -> SKNode? {
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks")
var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe!, error: nil)
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
So I'm getting a bug at the var sceneData = NSData saying: type of expression is ambiguous with more context. I'm very stuck
pathForResource
returns an optional.
dataWithContentsOfFile
expects a non-optional.
Unwrap the optional
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks")!
or do optional binding
if let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks") {
// path is safe
}
Actually the correct syntax of dataWithContentsOfFile
is
let sceneData = NSData(contentsOfFile:path, options: .DataReadingMappedIfSafe, error: nil)
and .DataReadingMappedIfSafe
never needs to be unwrapped.
EDIT:
The full code:
class func unarchiveFromFile(file : NSString) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks") {
// path is safe
let sceneData = NSData(contentsOfFile:path, options: .DataReadingMappedIfSafe, error: nil)
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
}
return nil
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.