8

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
    }
}
Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
dmr07
  • 1,388
  • 2
  • 18
  • 37
  • Which is it? Are you getting `nil` for the transform as stated in your question, or is the `session:didUpdate` function not being called at all, as stated in your code? – Hal Mueller Aug 05 '17 at 21:11
  • Sorry for the confusion. `session:didUpdate` is not being called at all. I tried accessing transform property in the `viewDidLoad` and got `nil` then figure the camera probably hasn't been initialized. Title has been updated. – dmr07 Aug 05 '17 at 21:55

2 Answers2

16

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.

1

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)
    }
}
Andy Jazz
  • 49,178
  • 17
  • 136
  • 220