'Auto flash on/off behaving weird with ambientIntensity of ARKit

I've implemented auto flash on-off using ARKit because I'm using ARKit on the same screen.

Implementation:

func session(_ session: ARSession, didUpdate frame: ARFrame) {
    let ambientIntensity = frame.lightEstimate?.ambientIntensity
    print(ambientIntensity)

    if ambientIntensity < 180 {
        // room is dark
        turnOnTorch()
    } else {
        // light is enough
        turnOffTorch()
    }

Here I'm using ARFrame's lightEstimate to get light intensity from the current environment.

Problem: When ambientIntensity variable's value is less than 180 then, the flash will be turned on. But when this delegate method calls itself and it will see that, oh yes we have the lights in the environment, but here we're getting light from the flashlight, not the sunlight. So ambientIntensity variable's value will be more than 180, so now the flashlight will be off. So this thing will go on and on. The flashlight will continuously turn on and off itself.

I've seen another solution is that some people are setting the light upon the screen brightness. But from my point of view, that is the wrong approach.

Is there any other solution is there that I can apply here? Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source