How to turn the iPhone camera flash on/off?

我怕爱的太早我们不能终老 提交于 2019-11-26 12:37:46

问题


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


回答1:


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



回答2:


I combined the timer with the above code.it worked for me...

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


来源:https://stackoverflow.com/questions/5882829/how-to-turn-the-iphone-camera-flash-on-off

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!