Swift: Access ARsession parameters through a UIbuttion click

114 views Asked by At

I am trying to print the ARsession's parameters like the following. It works when I do it within a session.

func session(_ session: ARSession, didUpdate frame: ARFrame) {
          guard let arCamera = session.currentFrame?.camera else { return }
          print("ARCamera ProjectionMatrix = \(arCamera.projectionMatrix)")
    }

Result:

ARCamera ProjectionMatrix = simd_float4x4([[1.774035, 0.0, 0.0, 0.0], [0.0, 2.36538, 0.0, 0.0], [-0.0011034012, 0.00073593855, -0.99999976, -1.0], [0.0, 0.0, -0.0009999998, 0.0]])

However, I would like to access/print the parameters when a button is clicked. I tried the following:

@IBAction private func startPressed() {
    print(ARSession.init().currentFrame?.camera.projectionMatrix)
}

But the result above returns nil. Am I missing some obvious and can someone help me on how to correct this so I can properly access the camera parameters when the button is clicked?

Thanks in advance!

1

There are 1 answers

4
Ivan Nesterenko On BEST ANSWER

You are initializing a new session by calling ARSession.init(), so there is no wonder it returns nil. You should use an instance of currently running ARSession instead. Assuming you are using ARSCNView to render the AR experience, correct code would look like this:

@IBAction private func startPressed() {
    if let matrix = sceneView.session.currentFrame?.camera.projectionMatrix {
       print(matrix)
    }
}