How to open the camera with flash

I am developing a simple application in which I need to constantly turn on the camera mode, not only when capturing an image. And the operating mode should be a camera, not a video recording. Is it possible? If so, how. Please help me with the code.

+6
source share
2 answers

You can use the method below to turn the camera on and off.

- (void)toggleFlashlight { AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; if (device.torchMode == AVCaptureTorchModeOff) { // Create an AV session AVCaptureSession *session = [[AVCaptureSession alloc] init]; // Create device input and add to current session AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil]; [session addInput:input]; // Create video output and add to current session AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init]; [session addOutput:output]; // Start session configuration [session beginConfiguration]; [device lockForConfiguration:nil]; // Set torch to on [device setTorchMode:AVCaptureTorchModeOn]; [device unlockForConfiguration]; [session commitConfiguration]; // Start the session [session startRunning]; // Keep the session around [self setAVSession:session]; [output release]; } else { [AVSession stopRunning]; [AVSession release], AVSession = nil; } } 

You can also use the following method along with displaying the camera,

 - (void) toggleFlashlight { // check if flashlight available Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice"); if (captureDeviceClass != nil) { AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; if ([device hasTorch] && [device hasFlash]){ [device lockForConfiguration:nil]; if (device.torchMode == AVCaptureTorchModeOff) { [device setTorchMode:AVCaptureTorchModeOn]; [device setFlashMode:AVCaptureFlashModeOn]; } else { [device setTorchMode:AVCaptureTorchModeOff]; [device setFlashMode:AVCaptureFlashModeOff]; } [device unlockForConfiguration]; } } } 

A source

+8
source

Use it for Swift 4

 func toggleFlash() { guard let device = AVCaptureDevice.default(for: AVMediaType.video) else {return} if device.hasTorch { do { try device.lockForConfiguration() if device.torchMode == AVCaptureDevice.TorchMode.on { device.torchMode = AVCaptureDevice.TorchMode.off //AVCaptureDevice.TorchModeAVCaptureDevice.TorchMode.off } else { do { try device.setTorchModeOn(level: 1.0) } catch { print(error) } } device.unlockForConfiguration() } catch { print(error) } } } 
+2
source

All Articles