我想监视手表电池状态,所以我为电池状态添加了 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
}
但是,当插入/拔出插头充电器时,它不会被调用。任何许可,否则我错过了什么?