I want to monitor watch battery state so i have added KVO for battery state like this
private func setupNotification() {
WKInterfaceDevice.current().addObserver(self,
forKeyPath: #keyPath(WKInterfaceDevice.batteryState),
options: [.new],
context: nil)
}
override public func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(WKInterfaceDevice.batteryState) {
switch WKInterfaceDevice.current().batteryState {
case .charging:
self.stopMonitoring()
case .unplugged:
if BatteryManager.batteryLevel > Constant.Battery.criticalValue {
self.startMonitoring()
}
default:
break
}
}
}
Also I have added before
func enableBatteryMonitoring() {
WKInterfaceDevice.current().isBatteryMonitoringEnabled = true
}
But it's not getting called, when in/out plug charger. Any permission or else what i'm missing?
As far as I saw from the documentation is not stated clearly that this property is KVO compliant.
In the WatchKit documentation they say:
So it seems that
isBatteryMonitoringEnabled
it just enable you to read the battery by asking its value (by polling) instead of observing it.