iosswiftscenekitarkitscnscene

[Swift]nil when loading scn files downloaded in runtime


I am working on a project to load a model into a ARKit powered app by scanning a qrCode. I have the qrCode working and .scn file downloaded into a .tmp file. However, when I tried to catch the scene by SCNScene(url:), all what returns is a nil.

I am wondering if it's because I copied the file too early --- before it finishes downloading, since the app freezes right after I scanned the qrCode.

Any suggestions would be appreciated. :D

2017-11-18 added download code

The template: http://www.jianshu.com/p/6ca4864b3600

func sessionSimpleDownload( scnurl: URL){
    let url = scnurl
    let request = URLRequest(url: url)
    let session = URLSession.shared
    var ls: String!

    let downloadTask = session.downloadTask(with: request,
    completionHandler: { (location:URL?, response:URLResponse?, error:Error?)
        -> Void in

        print("location:\(String(describing: location))")
        let locationPath = location!.path

        let documents:String = NSHomeDirectory() + "/Documents/max.scn"
        ls = NSHomeDirectory() + "/Documents"
        let fileManager = FileManager.default

        if (fileManager.fileExists(atPath: documents)){
            try! fileManager.removeItem(atPath: documents)
        }
        try! fileManager.moveItem(atPath: locationPath, toPath: documents)
        print("new location:\(documents)")

    })
    downloadTask.resume()

    self.Modelscene = SCNScene(named: "max.scn", inDirectory: ls)
}

Solution

  • Where is your download code? You shouldn't attempt to load the file until the completion handler is called. In any case you can check the file size with FileManager.default.attributesOfItem(atPath: ) and see if that matches what you expect.

    EDIT: Your problem is you call self.Modelscene = SCNScene(named: "max.scn", inDirectory: ls) right after downloadTask.resume(). That means you are opening the scene when the download has just started, not after it has finished. You need to put the scene assignment inside the completion handler so it happens when the download is complete.