2

我想监视手表电池状态,所以我为电池状态添加了 KVO,如下所示

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
        }
    }
}

我之前也加过

func enableBatteryMonitoring() {
    WKInterfaceDevice.current().isBatteryMonitoringEnabled = true
}

但是,当插入/拔出插头充电器时,它不会被调用。任何许可,否则我错过了什么?

4

1 回答 1

2

据我从文档中看到的,没有明确说明该属性符合 KVO。
在 WatchKit 文档中,他们说:

如果启用电池监控,则此属性设置为介于 0.0(0% 充电)和 1.0(100% 充电)之间的值。当 batteryState 属性设置为 WKInterfaceDeviceBatteryState.unknown 时(例如,禁用电池监控时),该值为 -1.0。

所以看起来isBatteryMonitoringEnabled它只是让你通过询问它的值(通过轮询)而不是观察它来读取电池。

于 2018-11-29T14:57:31.110 回答