skip to Main Content

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.

3

Answers


  1. Chosen as BEST ANSWER

    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
        }
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search