In my project, I have a SCNView encapsulated in UIViewRepresentable, that should resize in height according to the DragGesture of another view.
The issue is that when dragging, or after drag gesture ended, the memory usage is abnormally high. Checking for memory leaks in Instruments yielded no leaks. It also only occurs in a physical device, not in Simulator.
When using the Simulator,
The memory use is stable at around 19MB, regardless of resizing or not.
When using a physical device,
The memory use spiked badly upon each resize, and doesn't fall after end. (Worst I've seen was around 1.9GB of memory usage, before crash.)
Any experts here know the reason why it happens, and how to fix it? Thanks in advance.
UPDATE: I noticed that after DragGesture ended, if I were to move the camera of the SCNView, the memory will drop back to normal values.
Heres the code of the main ContentView.
Basically its a split view layout where if I were to adjust the RoundedRectangle (which acts as a handle), the top and bottom views will resize. It is when resizing that will cause the memory spike issue, which, at worst, will cause a crash, and Message from debugger: Terminated due to memory issue.
VStack {
SceneView()
.frame(height: (UIScreen.main.bounds.height / 2) + self.gestureTranslation.height)
RoundedRectangle(cornerRadius: 5)
.frame(width: 40, height: 6)
.foregroundColor(Color.gray)
.padding(2)
.gesture(DragGesture(coordinateSpace: .global)
.onChanged({ value in
self.gestureTranslation = CGSize(width: value.translation.width + self.prevTranslation.width, height: value.translation.height + self.prevTranslation.height)
})
.onEnded({ value in
self.gestureTranslation = CGSize(width: value.translation.width + self.prevTranslation.width, height: value.translation.height + self.prevTranslation.height)
self.prevTranslation = self.gestureTranslation
})
)
Rectangle()
.fill(Color.green)
.frame(height: (UIScreen.main.bounds.height / 2) - self.gestureTranslation.height)
}
}
Heres the code for the UIViewRepresentable wrapper for the SCNView.
struct SceneView: UIViewRepresentable {
typealias UIViewType = SCNView
func makeUIView(context: Context) -> SCNView {
let scene = SCNScene(named: "SceneAssets.scnassets/Cube.scn")
let view = SCNView()
view.scene = scene
view.allowsCameraControl = true
view.defaultCameraController.interactionMode = .orbitTurntable
view.defaultCameraController.inertiaEnabled = true
return view
}
func updateUIView(_ uiView: SCNView, context: Context) {
}
}
Here's the full test project that I've made to describe the issue: https://github.com/vincentneo/swiftui-scnview-memory-issue