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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5882829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:48:13  来源:igfitidea点击:

How to turn the iPhone camera flash on/off?

iosobjective-ciphoneios-camera

提问by Shahid Aslam

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

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

回答by Tibidabo

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

回答by girish

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