iphoneioscamerauiimagepickercontroller

How to access camera flash on UIImagePickerController?


I would like to know how to switch on the camera flash on the iPhone 4 with UIImagePickerController.

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerCameraDeviceFront] == YES)
{
    /// What code here ///
}
else
{
    NoFlash = [[UIAlertView alloc] initWithTitle:@"Uh-Oh"
                                         message:@"Your device doesn't have a flash camera"
                                        delegate:nil
                               cancelButtonTitle:@"mhmm, OK"
                               otherButtonTitles:nil];
    NoFlash.delegate = self;
    [NoFlash show];
    [NoFlash release];
}

I already read the UIImagePickerController Class Reference web page, but I didn't find the answer. Can someone please help me?


Solution

  • You can use this. Basically call 'toggleTorch' when you want to turn the flash on or off. Hopefully this is what you were looking for.

    - (void) toggleTorch {
    
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
        if ([device hasTorch] && [device hasFlash]){
    
            if (device.torchMode == AVCaptureTorchModeOff) {
    
                NSLog(@"It's currently off.. turning on now.");
    
                [power setImage:[UIImage imageNamed:@"on@2x.png"] forState:UIControlStateNormal];
    
                AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
                AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
    
                AVCaptureSession *session = [[AVCaptureSession alloc] init];
    
                [session beginConfiguration];
                [device lockForConfiguration:nil];
    
                [device setTorchMode:AVCaptureTorchModeOn];
                [device setFlashMode:AVCaptureFlashModeOn];
    
                [session addInput:flashInput];
                [session addOutput:output];
    
                [device unlockForConfiguration];
    
                [output release];
    
                [session commitConfiguration];
                [session startRunning];
    
                [self setTorchSession:session];
                [session release];
            }
            else {
    
                NSLog(@"It's currently on.. turning off now.");
    
                [power.imageView setImage:[UIImage imageNamed:@"off@2x.png"]];
    
                [torchSession stopRunning];
    
            }
    
        }
    
    }
    
    -(IBAction)powerBtn
    {
        [self toggleTorch];
    }