Reputation: 2326
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
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
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
Reputation: 90
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
Upvotes: 0