1

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?

4

1 回答 1

1

我的解决方案是从一个定期轮询电池状态和电量的单例对象发出自定义通知。如果您有更好的解决方案,请与我分享,我不太喜欢投票部分。

这是此示例代码

于 2018-04-13T19:28:07.560 回答