I have a routine that toggles the torch/flashlight setting....
func toggleTorch() {
guard let device = AVCaptureDevice.default(for: .video) else { return }
if device.hasTorch {
do {
try device.lockForConfiguration()
if device.torchMode == .off {
device.torchMode = .on
} else {
device.torchMode = .off
}
device.unlockForConfiguration()
} catch {
print("Torch could not be used")
}
} else {
print("Torch is not available")
}
}
This code is called by a button.
I originally had a light status parameter, but it was difficult to keep the value correct. If you swipe up to iconise the app, the light goes out, which is good, but the light status parameter would be still saying it was on. Toggling works fine for me.
There seems to be something else that turns the light off. Sometimes swiping between pages puts it out. Switching between one TabView and another seems to put it out. It seems to happen less if your gestures are smooth, but I can't figure out what the actual cause is.
Partial fix: The light goes off if the TabView is changed. I was switching between two TabViews for reasons that no longer apply. Taking this out makes it more robust, but it still happens. I wonder whether the swipes are being mistaken for the up-swipe leave app gesture, or something.
This has now stopped happening. Or at least happening enough to matter. I suspect the view that this control depended on was being redrawn. Anyway, if you have the same problem, maybe this is what to look for.