我有一个基于AVCam的视图控制器,并且添加了一个UIButton来切换手电筒。这是执行该操作的代码:

- (IBAction)toggleTorchLight:(id)sender {
// See: http://stackoverflow.com/questions/11726543/how-to-turn-flashlight-on-off-using-one-button
AVCaptureDevice *flashLight = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([flashLight isTorchAvailable] && [flashLight isTorchModeSupported:AVCaptureTorchModeOn]){
    if ([flashLight lockForConfiguration:nil]){
        if ([flashLight isTorchActive]) {
            [flashLight setTorchMode:AVCaptureTorchModeOff];
            [(UIButton *)sender setTintColor:[UIColor blackColor]];
        }
        else {
            [flashLight setTorchMode:AVCaptureTorchModeOn];
            [(UIButton *)sender setTintColor:[UIColor yellowColor]];
        }
        [flashLight unlockForConfiguration];
    }
}

您会注意到,当指示灯点亮时,我将按钮变黄了。问题在于,当应用程序发送到后台,视图控制器发生更改,显示警报视图控制器等时,手电筒灯也会熄灭。这些事件会关闭手电筒灯,但我还需要按下按钮又黑了。

除了在每种情况下都将按钮变黑以外,还有没有一种简单的方法,例如在灯熄灭时收到通知?我已经尝试过AVCaptureDeviceWasDisconnectedNotification,覆盖了becomeFirstResponderviewDidDisappear,但是都没有用。

有什么建议么?

最佳答案

首先定义一个上下文地址:

static void * TorchActiveContext = &TorchActiveContext;

然后在addObservers方法中:
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[videoDevice addObserver:self forKeyPath:@"torchActive" options:NSKeyValueObservingOptionNew context:TorchActiveContext];

removeObservers方法中:
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[videoDevice removeObserver:self forKeyPath:@"torchActive" context:TorchActiveContext];

observeValueForKeyPath
if (context == TorchActiveContext) {
    UIColor *color = ((AVCaptureDevice*)object).torchActive ? [UIColor yellowColor] : [UIColor blackColor];
    [self.torchLightButton setTintColor:color];
}

关于ios - 如何知道AVCaptureDevice手电筒灯何时熄灭?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40750787/

10-09 02:31