Phillip Phillip - 1 month ago 68
Swift Question

Xcode 8.1 Swift 3 Error: cannot convert value of type 'String' to expected argument type 'UnsafeMutableRawPointer'

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
}
}
}

Answer

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? { ...
Comments