Xcode 8.1 Swift 3 Error: Cannot convert value of type "String" to expected type of argument "UnsafeMutableRawPointer"

The line containing the var sceneData code is giving an error, apparently due to the "path" line. Does anyone know how to fix this? Thank!

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
        }
    }
}
+4
source share
1 answer

Data(bytesNoCopy: expects a pointer, not a string path.

API to read Datafrom disk Data(contentsOf, however it expects a 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 renamed the method to

class func unarchive(from file : String) -> SKNode? { ...
+7
source

Source: https://habr.com/ru/post/1659251/


All Articles