Search code examples
swiftxcodeaugmented-realityscenekitarkit

ARKit – How to track iPhone camera location during ARSession?


I'm very new to Xcode, so any and all help would be a godsend. I'm trying to write an app that saves the positional and rotational data from an iPhone at a set interval and saves it to a file. Right now, I'm not sure where to look when it comes to getting that data.

CoreMotion seems to not be enough so I'm using ARKit. I have a sceneView where I can see the origin and the feature points, but again, I'm stuck when it comes to where or even if the camera's position is tracked.


Solution

  • You can retrieve ARCamera's position and rotation via Transform Matrix (simd_float4x4). This data is contained inside every ARFrame of a running ARSession (for selfie or rear camera).

    let sceneView = ARSCNView(frame: .zero)
    sceneView.delegate = self
    
    let frame: ARFrame = sceneView.session.currentFrame!
    let cameraPosition: simd_float4 = frame.camera.transform.columns.3
    let cameraRotation: simd_float3 = frame.camera.eulerAngles
    

    The best place for these lines is SceneKit's renderer(_:didUpdate:for:) instance method. Take into consideration, that ARCamera transform values coming from IMU sensors are specially filtered.