iosswiftarkitarscnview

Camera freezes when I come back to viewcontroller containing ARSCNView. How to come and go in this view controller without ARSCNView stop working?


How I initialize the ARSCNView

var sceneView: ARSCNView?

override func viewDidLoad() {
    super.viewDidLoad()
    if ARConfiguration.isSupported{
        sceneView = ARSCNView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))

        view.addSubview(sceneView!)

        sceneView!.delegate = self
        // Show statistics such as fps and timing information
        sceneView!.showsStatistics = false

        // Create a new scene
        let scene = SCNScene(named: "totens.scnassets/Main.scn")!
        // Set the scene to the view
        sceneView!.scene = scene
     }
  }

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

        guard let referenceImages = ARReferenceImage.referenceImages(inGroupNamed: "TotensImages", bundle: nil) else { return }

        let configuration = ARImageTrackingConfiguration()
        configuration.trackingImages = referenceImages
        let options: ARSession.RunOptions = [.removeExistingAnchors]

        sceneView!.session.run(configuration, options: options)
 }

When a dismiss this view controller and try to restart session the camera stop appearing. Someone knows how to help me with this? thanks


Solution

  • Ok this is not the best way to fix it but it will probably work.

    On the ViewController where you have the ARScene View you have to initialize a bool flag that will check if you have to run the configuration. so..

    var shouldDoThingsInViewWillAppear: Bool = true
        override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    if shouldDoThingsInViewWillAppear {
    shouldDoThingsInViewWillAppear = false
            guard let referenceImages = ARReferenceImage.referenceImages(inGroupNamed: "TotensImages", bundle: nil) else { return }
    
            let configuration = ARImageTrackingConfiguration()
            configuration.trackingImages = referenceImages
            let options: ARSession.RunOptions = [.removeExistingAnchors]
    
            sceneView!.session.run(configuration, options: options)
        }
    
     }
    

    If this work that means that you shouldn't run twice the session or that you shouldn't add twice the tracking images.

    If not try to do the same of viewDidAppear instead of ViewWillAppear.

    If nether try to change the run method to

    sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])