Search code examples
iosxamarinkey-value-observing

How do I convert this code to detect camera focus?


I'm trying to convert my code for detecting the camera focus from Xcode/Swift to Xamarin/C#. [Aren't office politics great?] It doesn't seem to be working and I'm not sure why.

Swift Code:

private var _doneFocusing = false
let kFocusKeyPath = "adjustingFocus"

// this line in my startCamera method to watch for focus:
captureDevice.addObserver(self, forKeyPath:kFocusKeyPath, options: NSKeyValueObservingOptions.New, context: nil)


override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
    if keyPath == kFocusKeyPath {
        if let changeValue = change[NSKeyValueChangeNewKey] as? NSNumber {
            var adjustingFocus = (changeValue == 1)
            if adjustingFocus {
                _doneFocusing = false
            } else {
                _doneFocusing = true
            }
        }
    }
}

C# code. The ObserveValue method is not being called at all.

private bool _doneFocusing = false;
private const string kFocusKeyPath = "FocusKeyPath";

// this line in my startCamera method to watch for focus:
_captureDevice.AddObserver(this, kFocusKeyPath, NSKeyValueObservingOptions.New, IntPtr.Zero);


public override void ObserveValue(NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context)
{
    System.Diagnostics.Debug.WriteLine(keyPath);

    if (keyPath == kFocusKeyPath)
    {
        var changeValue = change.ValueForKey(ChangeNewKey) as NSNumber;
        if (changeValue == null)
        {
            return;
        }
        var adjustingFocus = (changeValue.Int16Value == 1);
        if (adjustingFocus)
        {
            _doneFocusing = false;
        }
        else
        {
            _doneFocusing = true;
        }

    }
}

Is there something I'm missing to get this working right?


Solution

  • Not sure why I changed the keyPath constant, but that was the problem.

    The keyPath has to specifically be "adjustingFocus"