dmr07
dmr07

Reputation: 1478

Not getting session `didUpdate` for camera position in ARKit

I'm new to swift, and I'm trying to get the location of the camera in the ARKit example, but it's giving me nil.

I used the solution for this question and set the delegate to self, but it's still not giving me the camera transform.

What am I doing wrong?

class ViewController: UIViewController, ARSCNViewDelegate {

    @IBOutlet var sceneView: ARSCNView!

    override func viewDidLoad() {
        super.viewDidLoad()
        sceneView.delegate = self
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let configuration = ARWorldTrackingSessionConfiguration()
        sceneView.session.run(configuration)
    }

    func session(_ session: ARSession, didUpdate frame: ARFrame) {
        print("Hello")     // DOES NOT RUN HERE
        let currentTransform = frame.camera.transform
    }
}

Upvotes: 8

Views: 4168

Answers (2)

Andy Jazz
Andy Jazz

Reputation: 58043

Alternatively, you can use an extension for ViewController, so you can add there a protocol ARSessionDelegate which ViewController conforms to:

extension ViewController: ARSessionDelegate {

    func session(_ session: ARSession, didUpdate frame: ARFrame) {

        let transform = session.currentFrame.camera.transform 
        print(transform)                              // NOW IT WORKS        
    }
}

class ViewController: UIViewController, ARSCNViewDelegate {

    @IBOutlet var sceneView: ARSCNView!

    override func viewDidLoad() {
        super.viewDidLoad()
        sceneView.delegate = self                     // ARSCNVIEW DELEGATE
        sceneView.session.delegate = self             // ARSESSION DELEGATE
    }   
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let configuration = ARWorldTrackingConfiguration()
        sceneView.session.run(configuration)
    }
}

Upvotes: 1

Shriphani Palakodety
Shriphani Palakodety

Reputation: 179

Simple fix, first your class definition:

class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate

Then you'll need to set yourself as the delegate like so:

sceneView.session.delegate = self

And then everything's going to work just right.

Upvotes: 17

Related Questions