iPhone:相机自动对焦观察器?

Sly*_*Sly 17 iphone notifications camera autofocus observer-pattern

我想知道是否可以在iPhone应用程序中收到有关自动对焦的通知?

IE,是否存在自动对焦开始,结束,如果成功或失败时被通知的方式......?

如果是这样,这个通知名称是什么?

Sly*_*Sly 44

我发现自动对焦开始/结束时我的案例的解决方案.它只是处理KVO(键值观察).

在我的UIViewController中:

// callback
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if( [keyPath isEqualToString:@"adjustingFocus"] ){
        BOOL adjustingFocus = [ [change objectForKey:NSKeyValueChangeNewKey] isEqualToNumber:[NSNumber numberWithInt:1] ];
        NSLog(@"Is adjusting focus? %@", adjustingFocus ? @"YES" : @"NO" );
        NSLog(@"Change dictionary: %@", change);
    }
}

// register observer
- (void)viewWillAppear:(BOOL)animated{
    AVCaptureDevice *camDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    int flags = NSKeyValueObservingOptionNew; 
    [camDevice addObserver:self forKeyPath:@"adjustingFocus" options:flags context:nil];

    (...)   
}

// unregister observer
- (void)viewWillDisappear:(BOOL)animated{
    AVCaptureDevice *camDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    [camDevice removeObserver:self forKeyPath:@"adjustingFocus"];

    (...)
}
Run Code Online (Sandbox Code Playgroud)

文档:


sas*_*ash 5

迅捷3

在您的AVCaptureDevice实例上设置焦点模式:

do {
     try videoCaptureDevice.lockForConfiguration()
     videoCaptureDevice.focusMode = .continuousAutoFocus
     videoCaptureDevice.unlockForConfiguration()
} catch {}
Run Code Online (Sandbox Code Playgroud)

添加观察者:

videoCaptureDevice.addObserver(self, forKeyPath: "adjustingFocus", options: [.new], context: nil)
Run Code Online (Sandbox Code Playgroud)

覆写observeValue

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

    guard let key = keyPath, let changes = change else { 
        return
    }

    if key == "adjustingFocus" {

        let newValue = changes[.newKey]
        print("adjustingFocus \(newValue)")
    }
}
Run Code Online (Sandbox Code Playgroud)