Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn the iPhone camera flash on/off?

How can I turn the iPhone's LED camera flash on/off programatically?

like image 580
Shahid Aslam Avatar asked May 04 '11 11:05

Shahid Aslam


People also ask

How do I turn the flash on my iPhone 13 Camera?

Here's how to enable camera flash on an iPhone 11, 12, SE (2nd generation), 13, and so on: Open the Camera app and swipe up or tap the arrow button on the top. Tap the flash icon. Tap On to set the iPhone camera flash to always-on.


2 Answers

#import <AVFoundation/AVFoundation.h> 

...

- (void) turnTorchOn: (bool) on {      // 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 (on) {                 [device setTorchMode:AVCaptureTorchModeOn];                 [device setFlashMode:AVCaptureFlashModeOn];                 //torchIsOn = YES; //define as a variable/property if you need to know status              } else {                 [device setTorchMode:AVCaptureTorchModeOff];                 [device setFlashMode:AVCaptureFlashModeOff];                 //torchIsOn = NO;                         }             [device unlockForConfiguration];         }     } } 
like image 159
Tibidabo Avatar answered Sep 30 '22 17:09

Tibidabo


I combined the timer with the above code.it worked for me...

 - (void)viewDidLoad         {          [super viewDidLoad];           myTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self                    selector:@selector(toggleFlashlight) userInfo:nil repeats:YES];         // Do any additional setup after loading the view from its nib.         }        - (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];                 //torchIsOn = YES;             }             else              {                 [device setTorchMode:AVCaptureTorchModeOff];                 [device setFlashMode:AVCaptureFlashModeOff];                // torchIsOn = NO;                         }             [device unlockForConfiguration];         }     } } 
like image 28
girish Avatar answered Sep 30 '22 18:09

girish