Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

xcode

swift

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
        }
    }
}
like image 500
Phillip Avatar asked Feb 06 '23 19:02

Phillip


1 Answers

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? { ...
like image 135
vadian Avatar answered Apr 19 '23 22:04

vadian