Activate the LED for a flashlight app

15,142

Solution 1

Use the following:

AVCaptureSession * session = [[AVCaptureSession alloc] init];

[session beginConfiguration];

AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn]; 
[device unlockForConfiguration];

AVCaptureDeviceInput * flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
if (flashInput){
    [session addInput:flashInput];
}
    AVCaptureVideoDataOutput * output = [[AVCaptureVideoDataOutput alloc] init];
    [session addOutput:output];
        [output release];
    [session commitConfiguration];  
    [session startRunning];
}
[self setTorchSession:session];
[session release];

(From a discussion on iPhoneDevSDK)

Solution 2

Here is a shorter version you can now use to turn the LED on or off:

- (void)torchOnOff: (BOOL) onOff
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        [device setTorchMode: onOff ? AVCaptureTorchModeOn : AVCaptureTorchModeOff];
        [device unlockForConfiguration];
    }
}

UPDATE: (March 2015)

You can also set the brightness of the torch:

- (void)setTorchToLevel:(float)torchLevel
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        if (torchLevel <= 0.0) {
            [device setTorchMode:AVCaptureTorchModeOff];
        }
        else {
            if (torchLevel >= 1.0)
                torchLevel = AVCaptureMaxAvailableTorchLevel;
            BOOL success = [device setTorchModeOnWithLevel:torchLevel   error:nil];
        }
        [device unlockForConfiguration];
    }
}
Share:
15,142
David  Holmes
Author by

David Holmes

Updated on June 14, 2022

Comments

  • David  Holmes
    David Holmes almost 2 years

    I'm trying to make a flashlight app for my iPhone. I have an iPhone 4 and would like to utilize the LED on my iPhone for my project. Can anyone help me to get started with that?