Search code examples
iosswiftscenekitarkitarscnview

Check if ARSession is running (ARKit)


I have an ARSCNView that can occasionally pause its session depending on the situation. Is there a way to check if its session is running?

Something like this:

class myARView: ARSCNView {
    ...
    func foo() {

        if(session.running) {
            // do stuff
        }
    }
    ...
}

Solution

  • At this moment, it seems there isn't a way to check if the session is running, by ARSession object itself. However, by implementing ARSCNViewDelegate, you can get notified whenever your session is interrupted or the interruption ends.

    One way to achieve your goal is to set a boolean and update it whenever you pause/resume the session, and check its value in your functions.

    class ViewController: UIViewController, ARSCNViewDelegate {
    
        var isSessionRunning: Bool
    
        func foo() {
            if self.isSessionRunning {
                // do stuff
            }
        }
    
        func pauseSession() {
            self.sceneView.session.pause()
            self.isSessionRunning = false
        }
    
        func runSession() {
            let configuration = ARWorldTrackingConfiguration()
            sceneView.session.run(configuration)
            self.isSessionRunning = true
        }
    
        // ARSCNViewDelegate:
        func sessionWasInterrupted(_ session: ARSession) {
            self.isSessionRunning = false
        }
    
        func sessionInterruptionEnded(_ session: ARSession) {
            self.isSessionRunning = true
        }
    }