3

I built a camera app for auto capture. I want to keep the flash on as long as the camera is on. I set the following code :

 cameraDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
    if (cameraDevice.hasTorch) {
        do {
            try cameraDevice.lockForConfiguration()

            if cameraDevice.isTorchActive {
                cameraDevice.torchMode = AVCaptureTorchMode.on

            } else {
                // sets the torch intensity to 100%
               try  cameraDevice.setTorchModeOnWithLevel(0.8)
            }

            cameraDevice.unlockForConfiguration()
        } catch {
            print(error)
        }
    }

But when I run the app, it only flashes for one time and then goes off. How can I solve this problem?

Rubaiyat Jahan Mumu
  • 3,887
  • 1
  • 33
  • 35

1 Answers1

11

Call this method

Inside your camera active/Open func or When device camera active -

   func flashActive() {
    if let currentDevice = AVCaptureDevice.default(for: AVMediaType.video), currentDevice.hasTorch {
        do {
            try currentDevice.lockForConfiguration()
            let torchOn = !currentDevice.isTorchActive
            try currentDevice.setTorchModeOn(level:1.0)//Or whatever you want
            currentDevice.torchMode = torchOn ? .on : .off
            currentDevice.unlockForConfiguration()
        } catch {
            print("error")
        }
    }
}
iDeveloper
  • 2,339
  • 2
  • 24
  • 38