I have a UIViewControllerRepresentable struct as follows.
struct ImagePicker: UIViewControllerRepresentable {
@Binding var isShown: Bool
@Binding var image: UIImage?
@Binding var didTapCapture: Bool
@Binding var flash: Bool?
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
uiViewController.showsCameraControls = false
if (didTapCapture == true){
uiViewController.takePicture()
didTapCapture = false
}
}
func makeCoordinator() -> ImagePickerCoordinator {
return ImagePickerCoordinator(isShown: $isShown, image: $image)
}
func toggleFlash() {
guard let device = AVCaptureDevice.default(for: AVMediaType.video) else { return }
guard device.hasTorch else { return }
do {
try device.lockForConfiguration()
if (device.torchMode == AVCaptureDevice.TorchMode.on) {
device.torchMode = AVCaptureDevice.TorchMode.off
} else {
do {
try device.setTorchModeOn(level: 1.0)
} catch {
print(error)
}
}
device.unlockForConfiguration()
} catch {
print(error)
}
}
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let picker = UIImagePickerController()
self.toggleFlash() // does not work
picker.delegate = context.coordinator
picker.sourceType = .camera
picker.showsCameraControls = false
picker.modalPresentationStyle = .fullScreen
return picker
}
}
For reference, here is the corresponding ImagePickerCoordinator.
class ImagePickerCoordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@Binding var isShown: Bool
@Binding var image: UIImage?
init(isShown: Binding<Bool>, image: Binding<UIImage?>) {
_isShown = isShown
_image = image
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//self.toggleFlash()
let uiImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
image = uiImage
isShown = false
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
isShown = false
}
}
When I open the camera, the flash briefly blinks on and then turns off when the camera view appears. I want to keep it on while the camera is showing. How can I do this with my current code?