WWDC 2021 session 10047 recommends to observe changes in AVCaptureDevice.isCenterStageEnabled which is a class property. But how exactly do we observe a class property in Swift?
How to observe AVCaptureDevice.isCenterStageEnabled?
There is a great article about Using Key-Value Observing in Swift.
I recommend starting with that article, and then posting back here if you are still having issues observing the center stage enabled property.
@gchiste I already tried the following code but compiler gives errors saying it can not observe a class property.
AVCaptureDevice.observe(\.isCenterStageEnabled, options: [.new, .old]) { controller, value in
NSLog("Value \(value)")
}
Instance member 'observe' cannot be used on type 'AVCaptureDevice'; did you mean to use a value of this type instead?
Hey,
Thanks for reading over the article, I see now that it doesn't cover the case of a class property.
Give something like this a try:
// Add some NSObject (probably a UIViewController) as an observer of the class property, specifying the options you'd like.
AVCaptureDevice.self.addObserver(self, forKeyPath: "centerStageEnabled", options: [.initial, .new], context: nil)
// Override observeValue on your object and handle any values that you expect it to be observing.
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "centerStageEnabled" {
guard let object = object as? AVCaptureDevice.Type else { return }
print(object.isCenterStageEnabled)
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}