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

Time:01-08

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.

CodePudding user response:

I think on demand resources could be a solution to this: https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/On_Demand_Resources_Guide/index.html

https://www.raywenderlich.com/520-on-demand-resources-in-ios-tutorial

CodePudding user response:

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
    }

CodePudding user response:

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.

  •  Tags:  
  • Related