Search code examples
swiftswiftuiaugmented-realityarkitrealitykit

How to get the name of the tracked image in Swift with RealityKit?


I have multiple AR Reference images and I want to know which one I am currently tracking. How can I do that? Here is my code:

let configuration = ARImageTrackingConfiguration()

guard let trackedImages = ARReferenceImage.referenceImages(inGroupNamed: "Photos", bundle: Bundle.main) else {
      print("No images available")
      return
  }
    
  configuration.trackingImages = trackedImages
  configuration.maximumNumberOfTrackedImages = 1
  sceneView.session.run(configuration)

Solution

  • You'll want to use the renderer(_:didAdd:for:) method. When your app detects an image it recognizes it will add an anchor. You can pull the name of that image from your asset catalogue.

    Add this to your ARSCNViewDelegate class:

    func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
        guard let imageAnchor = anchor as? ARImageAnchor else { return }
        let image = imageAnchor.referenceImage
        // this is one means of getting the name of the image
        if let trackedImage = image.name {
            print(trackedImage)
        }
    }