How do you set a device's flash mode in Swift 4?
I've been facing the same problem. Unfortunately, many useful methods got deprecated in iOS10 and 11. Here is how I managed to resolve it:
AVCapturePhotoSettings object is unique and cannot be reused, so you need to get new settings every time using this method:
/// the current flash mode
private var flashMode: AVCaptureDevice.FlashMode = .auto
/// Get settings
///
/// - Parameters:
/// - camera: the camera
/// - flashMode: the current flash mode
/// - Returns: AVCapturePhotoSettings
private func getSettings(camera: AVCaptureDevice, flashMode: AVCaptureDevice.FlashMode) -> AVCapturePhotoSettings {
let settings = AVCapturePhotoSettings()
if camera.hasFlash {
settings.flashMode = flashMode
}
return settings
}
As you can see, lockConfiguration is not needed.
Then simply use it while capturing photo:
@IBAction func captureButtonPressed(_ sender: UIButton) {
let settings = getSettings(camera: camera, flashMode: flashMode)
photoOutput.capturePhoto(with: settings, delegate: self)
}
Hope it will help.
For objective C:
- (IBAction)turnTorchOn: (UIButton *) sender {
sender.selected = !sender.selected;
BOOL on;
if (sender.selected) {
on = true;
} else {
on = false;
}
// check if flashlight available
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCapturePhotoSettings *photosettings = [AVCapturePhotoSettings photoSettings];
if ([device hasTorch] && [device hasFlash]) {
[device lockForConfiguration:nil];
if (on) {
[device setTorchMode:AVCaptureTorchModeOn];
photosettings.flashMode = AVCaptureFlashModeOn;
//torchIsOn = YES; //define as a variable/property if you need to know status
} else {
[device setTorchMode:AVCaptureTorchModeOff];
photosettings.flashMode = AVCaptureFlashModeOn;
//torchIsOn = NO;
}
[device unlockForConfiguration];
}
}
}