Dynamically change background of SCNView in Swift

I am making an iOS app that - in its essential part - receives JPEG images frame by frame via TCP.

Another part of the app has an ARSCNView, which background needs to be set dynamically from these frames.

My pseudo code looks like this:

while(phase == 1) {
    let bytes = try tcpSocket.read(into: &jpegData)
    sceneView.scene.background.contents = UIImage(data: jpegData)

    // or the other way

    let bgempty = backgroundImage == nil
    backgroundImage = UIImage(data: jpegData)
    if(bgempty) {
       sceneView.scene.background.contents = backgroundImage
    }
}

That's pretty much it. Either way, this loop creates a memory leak. Same when I use CGImage

How would you assign an ever changing background to ARSCNView, avoiding memory leaks?

Upvotes: 1

Views: 622

Answers (1)

M Reza
M Reza

Reputation: 19758

One solution would be using autoreleasepool block. This could ensure the footprint of memory keeps minimum. The loop you use takes a lot of device’s memory, to optimize this code you could add autorelease pool as follows:

while(phase == 1) {
    autoreleasepool {
        let bytes = try tcpSocket.read(into: &jpegData)
        sceneView.scene.background.contents = UIImage(data: jpegData)

        // or the other way

        let bgempty = backgroundImage == nil
        backgroundImage = UIImage(data: jpegData)
        if(bgempty) {
            sceneView.scene.background.contents = backgroundImage
        }
    }
}

Upvotes: 1

Related Questions