如何打开/关闭iPhone相机闪光灯?

时间:2011-05-04 11:46:21

标签: ios objective-c iphone ios-camera

如何以编程方式打开/关闭iPhone的LED相机闪光灯?

2 个答案:

答案 0 :(得分:79)

#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];
        }
    } }

答案 1 :(得分:23)

我将计时器与上面的代码结合起来。这对我有用......

 - (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];
        }
    } }