Watch OS: Swift KVO for BatteryState is not working

321 views Asked by At

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?

1

There are 1 answers

3
Andrea On

As far as I saw from the documentation is not stated clearly that this property is KVO compliant.
In the WatchKit documentation they say:

If battery monitoring is enabled, this property is set to a value between 0.0 (0% charge) and 1.0 (100% charge). When the batteryState property is set to WKInterfaceDeviceBatteryState.unknown (for example, when battery monitoring is disabled), the value is -1.0.

So it seems that isBatteryMonitoringEnabled it just enable you to read the battery by asking its value (by polling) instead of observing it.