'How to properly end a ARView that uses a Reality Composer project?

My project has a few views before it call a ARview with a reality composer project. I enabled the coaching view in it using the demo code that apple provides. My problem is. If I make a button to go back from that view and call it again, the camera starts to flick from second to second. If I do it again, the flick increases until that, if I do it again, the program crashes. How can I make that view completely new, like the first time I loaded it? I’ve tried removing the anchor from the view.session. Tried pausing the ar session. Could anyone help me with that? This is my code


import UIKit
import RealityKit
import ARKit

class ARHomeViewController: UIViewController {

    @IBOutlet var arView: ARView!
    @IBOutlet weak var coachingOverlay: ARCoachingOverlayView!

    override func viewDidLoad()
    {
        super.viewDidLoad()

        presentCoachingOverlay()

        addScene()
    }

    /// Begins the coaching process that instructs the user's movement during
    /// ARKit's session initialization.
    func presentCoachingOverlay() {
        coachingOverlay.session = arView.session
        coachingOverlay.delegate = self
        coachingOverlay.goal = .horizontalPlane
        coachingOverlay.activatesAutomatically = false
        self.coachingOverlay.setActive(true, animated: true)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        // Prevent the screen from being dimmed to avoid interuppting the AR experience.
        UIApplication.shared.isIdleTimerDisabled = true
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        arView?.session.pause()
    }

    func addScene()
    {
        guard let anchor = try? ExperienciaCasa.loadMenu() else { return }

        anchor.generateCollisionShapes(recursive: true)

        arView.scene.addAnchor(anchor)
    }

}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source