How to turn the iPhone camera flash on/off?

Shahid Aslam picture Shahid Aslam · May 4, 2011 · Viewed 56.6k times · Source

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

Answer

Tibidabo picture Tibidabo · Apr 7, 2012
#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];
        }
    } }