Hope
Hope

Reputation: 2326

Is it possible to save an object to disk as SceneKit SCN file created in an iOS app?

I am creating some geometries in SceneKit with

SCNGeometry(sources: [vertexSource, normalSource], elements: [element])

But I do not want save huge number of sources and elements to disk and recreate them every time app started.

Is there a way to save created objects as SCN files to the disk in an iOS application.

Upvotes: 0

Views: 624

Answers (3)

mnuages
mnuages

Reputation: 13462

It is possible to put objects (for instance a SCNGeometry instance) in a scene and then call -[SCNScene writeToURL:options:delegate:progressHandler:] to save it on the disk.

Alternatively, most SceneKit classes conform to the NSSecureCoding protocol which means they can be archived individually (without a scene).

For instance you can call +[NSKeyedArchiver archivedDataWithRootObject:requiringSecureCoding:error:] with the SCNGeometry instance as the root object and you'll obtain a NSData onto which you can call -writeToURL:options:error:.

In fact this is what the -[SCNScene writeToURL:options:delegate:progressHandler:] method does internally, with the scene as the root object.

Upvotes: 2

Hope
Hope

Reputation: 2326

I think this is working;

First you save scene with objects you want to save as .scn file

 func saveScene(){
    let sceneToSave = scnView.scene
    let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let url = documentsPath.appendingPathComponent( "test.scn")
    scene2!.write(to: url, options: nil, delegate: nil, progressHandler: nil)
}

To get objects you saved;

    func loadObject(){
      let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
      let url = documentsPath.appendingPathComponent( "test.scn")
      var testGeometry = try! SCNScene(url: url, options: nil).rootNode.childNode(withName: "testGeometry", recursively: true)?.geometry
    }

Upvotes: 2

Related Questions