Is there any way to be notified of changes in battery state in real time without periodically checking for the state?
I tried finding an equivalent to UIDevice.UIDeviceBatteryStateDidChangeNotification
available on iOS, but WKInterfaceDevice
for watchOS doesn't seem to offer this Notification.
Even though the Apple doc specifies that classes in UIKit
do not support KVO, and it is probably the same deal with WatchKit
, I still tried registering an observer on WKInterfaceDevice.current().batteryState
as follow, but it doesn't notify of changes
WKInterfaceDevice.current().isBatteryMonitoringEnabled = true
batteryObserver = WKInterfaceDevice.current().observe(\.batteryState) {
[weak self] _, _ in self?.onBatteryStateChange()
}
Does anyone know how to accomplish this without polling for the state periodically?
My solution was to make a custom notification from a singleton object that polls the battery state and level at regular intervals. If ever you have a better solution please share it with me, I'm not so fond of the polling part.