如何知道 AVCaptureDevice 手电筒灯何时关闭?

How to know when AVCaptureDevice torch light turns off?

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

- (IBAction)toggleTorchLight:(id)sender {
// See: 
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,其中 none 有效。

有什么建议吗?

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

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