我正在尝试使用Key Value Observation来检测AVCaptureDevice的torchMode变量的变化。我遇到一个问题,即switch语句无法识别该值(这是一个枚举)。有什么想法吗?我知道程序通过交换机进入线路,然后立即跳过所有情况。这是相关的代码:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == CapturingStillImageContext)
{
BOOL isCapturingStillImage = [change[NSKeyValueChangeNewKey] boolValue];
if (isCapturingStillImage)
{
[self runStillImageCaptureAnimation];
}
}
else if (context == RecordingContext)
{
BOOL isRecording = [change[NSKeyValueChangeNewKey] boolValue];
dispatch_async(dispatch_get_main_queue(), ^{
if (isRecording)
{
[[self record] setTitle:NSLocalizedString(@"-", @"Recording button stop title") forState:UIControlStateNormal];
[[self record] setEnabled:YES];
}
else
{
[[self record] setTitle:NSLocalizedString(@"+", @"Recording button record title") forState:UIControlStateNormal];
[[self record] setEnabled:YES];
}
});
}
else if (context == SessionRunningAndDeviceAuthorizedContext)
{
BOOL isRunning = [change[NSKeyValueChangeNewKey] boolValue];
dispatch_async(dispatch_get_main_queue(), ^{
if (isRunning)
[[self record] setEnabled:YES];
else
[[self record] setEnabled:NO];
});
}
else if (context == TorchContext) {
id torchValue = [change objectForKey: NSKeyValueChangeNewKey];
NSString* title;
switch((AVCaptureTorchMode)torchValue) {
case AVCaptureTorchModeAuto: title = @"Auto"; break;
case AVCaptureTorchModeOff: title = @"Off"; break;
case AVCaptureTorchModeOn: title = @"On"; break;
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.torch setTitle:title forState:UIControlStateNormal];
//NSLog(self.torch);
});
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
为键值添加观察者的代码:
- (void)viewWillAppear:(BOOL)animated
{
[self.navigationController setNavigationBarHidden:YES animated:NO];
dispatch_async([self sessionQueue], ^{
[self addObserver:self forKeyPath:@"sessionRunningAndDeviceAuthorized" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:SessionRunningAndDeviceAuthorizedContext];
[self addObserver:self forKeyPath:@"stillImageOutput.capturingStillImage" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:CapturingStillImageContext];
[self addObserver:self forKeyPath:@"movieFileOutput.recording" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:RecordingContext];
[self addObserver:self forKeyPath:@"videoDeviceInput.device.torchMode" options:(NSKeyValueObservingOptionNew) context:TorchContext];
...
}
答案 0 :(得分:2)
我解决了这个问题。我不确定这是否是最优雅的解决方案,但我只是将值转换为NSNumber并获得整数值,然后将其放入交换机中。这是代码:
int torchValue = ((NSNumber*)[change objectForKey: NSKeyValueChangeNewKey]).integerValue;
NSString* title;
switch(torchValue) {
case AVCaptureTorchModeAuto: title = @"Auto"; break;
case AVCaptureTorchModeOff: title = @"Off"; break;
case AVCaptureTorchModeOn: title = @"On"; break;
}