See the best answer below: stack overflow
Old answer:
Firstly, in your AppDelegate.h file:
Then in your AppDelegate.m file:
@implementation AppDelegate @synthesize torchSession; - (void)dealloc { [torchSession release]; [super dealloc]; } - (id) init { if ((self = [super init])) { // initialize flashlight // test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice"); if (captureDeviceClass != nil) { AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; if ([device hasTorch] && [device hasFlash]){ if (device.torchMode == AVCaptureTorchModeOff) { NSLog(@"Setting up flashlight for later use..."); AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil]; AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init]; AVCaptureSession *session = [[AVCaptureSession alloc] init]; [session beginConfiguration]; [device lockForConfiguration:nil]; [session addInput:flashInput]; [session addOutput:output]; [device unlockForConfiguration]; [output release]; [session commitConfiguration]; [session startRunning]; [self setTorchSession:session]; [session release]; } } } } return self; }
Then anytime you want to enable it, just do the following:
// test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice"); if (captureDeviceClass != nil) { AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; [device lockForConfiguration:nil]; [device setTorchMode:AVCaptureTorchModeOn]; [device setFlashMode:AVCaptureFlashModeOn]; [device unlockForConfiguration]; }
And similarly to disable it:
// test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice"); if (captureDeviceClass != nil) { AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; [device lockForConfiguration:nil]; [device setTorchMode:AVCaptureTorchModeOff]; [device setFlashMode:AVCaptureFlashModeOff]; [device unlockForConfiguration]; }
iwasrobbed Jul 29 '10 at 10:19 2010-07-29 22:19
source share