swiftarkitscnscene

Get an URL from SCNScene


In the apple example code for ARKit, they provided a VirtualObjectclass that load Scn files from Models.scnassets.

 static let availableObjects: [VirtualObject] = {
    let modelsURL = Bundle.main.url(forResource: "Models.scnassets", withExtension: nil)!

    let fileEnumerator = FileManager().enumerator(at: modelsURL, includingPropertiesForKeys: [])!

    return fileEnumerator.compactMap { element in
        let url = element as! URL

        guard url.pathExtension == "scn" && !url.path.contains("lighting") else { return nil }

        return VirtualObject(url: url)
    }
}()

Let's say I have a SCNScene that download from a sever, the first question is, this SCNScene is similar to scn files? if yes, how can I add this SCNScene to the above function, and get its URL to add it in the return VirtualObject(url: url) ? I stuck in this part for days, would be appreciated if anyone can help me.


Solution

  • You can store it in the file manager and get url from there

    if scene is your SCNScene:

    static let availableObjects: [VirtualObject] = {
        
        var virtualObjects: [VirtualObject] = []
    
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let url = paths.appendingPathComponent("chair.scn")
        
        scene.write(to: url, options: nil, delegate: nil) { float, error, pointer in
            if let error = error {
                print(error.localizedDescription)
                return
            }
        }
        
        if let objects = VirtualObject(url: url) {
            virtualObjects.append(objects)
        }
        return virtualObjects
    }