我有一个基于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
,覆盖becomeFirstResponder
和viewDidDisappear
,但都没有。
有什么建议吗?
答案 0 :(得分:1)
首先定义一个上下文地址:
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];
}