2016-11-22 67 views
1

我有一个基于AVCam的视图控制器,我添加了一个UIButton来切换手电筒灯。以下是执行该操作的代码:如何知道AVCaptureDevice手电筒灯熄灭的时间?

- (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,他们都没有工作。

有什么建议吗?在addObservers方法

static void * TorchActiveContext = &TorchActiveContext; 

然后::

+0

你有没有尝试使用AppDelegate状态发射你自己的通知?例如'applicationWillResignActive'例如 – Nathaniel

+0

您可以使用KVO观察'torchActive'。 –

+0

@RhythmicFistman KVO完美运作!使用[this](http://stackoverflow.com/questions/28489223/torchlevel-kvo-ios)为指导 –

回答

1

首先定义一个上下文地址

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