'How to get the reason of isFlashAvailable and isTorchAvailable return false - Reason?

So I build a custom camera app, and in my camera app it has a flash button, I need to update the device flash mode according to the user tap action. Apparently, I stumble to property isFlashAvailable for flash mode and isTorchAvailable for torch mode. It seems pretty straightforward but if this property returns false, I need to know the reason why flash or torch is unavailable. Is there any suggestion of how to get any specific reason for this case?

In docs, it only said that

for example, the device overheats and needs to cool off.

It is fine if that is the only possible reason, but I am not sure, and maybe you have any suggestion about this?

And here are some snippets of my implementation

    /// Updates the device's flash on, auto, or off and returns wether it is successfull or not.
    @discardableResult
    public func updateFlash(mode: AVCaptureDevice.FlashMode) -> Bool {
        guard let device = AVCaptureDevice.default(for: .video),
              device.hasFlash,
              device.isFlashAvailable else { return false }

        flashMode = mode
        return true
    }

    /// Updates the device's torch on, auto, or off and returns wether it is successfull or not.
    @discardableResult
    public func updateTorch(mode: AVCaptureDevice.TorchMode) -> Bool {
        guard let device = AVCaptureDevice.default(for: .video),
              device.hasTorch,
              device.isTorchAvailable,
              device.isTorchModeSupported(mode) else { return false }

        do {
            try device.lockForConfiguration()
            device.torchMode = mode
            device.unlockForConfiguration()
            return true
        } catch {
            return false
        }
    }

Reference

https://developer.apple.com/documentation/avfoundation/avcapturedevice/1624627-isflashavailable#declaration https://developer.apple.com/documentation/avfoundation/avcapturedevice/1624626-istorchavailable



Solution 1:[1]

Try to use this function to on/off the torch.

private func toggleTorch(status: Bool) {
    guard let device = AVCaptureDevice.default(for: .video) else { return }
    device.toggleTorch(on: status)
}

and use this function like this where you want to update the torch.

self.toggleTorch(status: true) OR
self.toggleTorch(status: false)

Edited

import AVFoundation

extension AVCaptureDevice {
    func toggleTorch(on: Bool) {
        guard hasTorch, isTorchAvailable else {
            print("Torch is not available")
            return
        }
        do {
            try lockForConfiguration()
            torchMode = on ? .on : .off
            unlockForConfiguration()
        } catch {
            print("Torch could not be used \(error)")
        }
    }
}

Sources

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

Source: Stack Overflow

Solution Source
Solution 1