dr_pepper dr_pepper - 1 month ago 21
iOS Question

How can the rear camera flash be forced to on in Swift 3?

I am attempting to force the flash to be on for an imagePicker but when I run the following code, it defaults to off. Does anything else need to be done to force the flash on in Swift 3?

let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
imagePicker.allowsEditing = false
imagePicker.cameraFlashMode = UIImagePickerControllerCameraFlashMode.on
imagePicker.cameraDevice = UIImagePickerControllerCameraDevice.rear;
self.present(imagePicker, animated: true, completion: nil)


A previous question was asked here for an older version of Swift:
Camera Flash Turn Auto/On/Off with UIImagePickerController in IOS - Swift

But, there appears to be some subtleties that I am missing to get it to work in Swift 3.

Answer

Set the camera flash mode in a completion closure as follows:

  self.present(imagePicker, animated: true)
  {
      imagePicker.cameraFlashMode = UIImagePickerControllerCameraFlashMode.on
  }

The full source is as follows:

  let imagePicker = UIImagePickerController()
  imagePicker.delegate = self
  imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
  imagePicker.allowsEditing = false
  imagePicker.cameraDevice = UIImagePickerControllerCameraDevice.rear;

  self.present(imagePicker, animated: true)
  {
      imagePicker.cameraFlashMode = UIImagePickerControllerCameraFlashMode.on
  }

Verified that this works with Swift 3, but not sure if it helps for older versions.