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?
Replies
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)
}
}
-
This way certainly works but it is a legacy way of observing properties. I was thinking if there is modern Swift KVO based method for the same. Sorry to omit those details in my question here , I should have mentioned the details like i mentioned on stackoverflow.(https://stackoverflow.com/questions/69505085/swift-kvo-addobserver-observevalue-for-class-objects)
-
I’m not aware of another way to do it, I recommend that you take this question over to the Swift Forums, someone there may know a “Swiftier” approach to observing class properties.
-
Thanks for the answer. I will definitely post it on Swift forums.