2016-11-22 65 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]; 
}