Search code examples
swiftabstract-classaugmented-realityscenekitarkit

ARKit – Light Estimation


I am getting an error about init() not being available for ARLightEstimate.

Code:

class LightSensorManager {

    let lightEstimate = ARLightEstimate()  // <-- error is here
    var ambientLightIntensity: CGFloat

    init() {
        ambientLightIntensity = lightEstimate.ambientIntensity
    }
}

Error:

/*   'init()' is unavailable    */

API to ARLightEstimation - ARKit

I assume it is an abstract class? But I cannot find a concrete subclass of it. I only want to use the ambient Light sensor from this API to detect ambient Light.


Solution

  • Here's how you can use Light Estimation in ARKit – Full code version is HERE:

    • Enable Light Estimation in viewWillAppear(_:) instance method:

       let configuration = ARWorldTrackingConfiguration()
       configuration.lightEstimationEnabled = true
      
    • Update lighting in renderer(_:updateAtTime:) SceneKit's instance method:

       func renderer(_ renderer: SCNSceneRenderer, 
              updateAtTime time: TimeInterval) {
      
           guard let lightEstimate = sceneView.session.currentFrame?.lightEstimate 
           else { return } 
           spotLightNode.light?.intensity = lightEstimate.ambientIntensity
       }