gpt4 book ai didi

swift - 观看操作系统 : Swift KVO for BatteryState is not working

转载 作者:可可西里 更新时间:2023-11-01 01:07:58 24 4
gpt4 key购买 nike

我想监控 watch 电池状态,所以我像这样为电池状态添加了 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
}

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

最佳答案

据我所见,文档中没有明确说明此属性符合 KVO。
他们在 WatchKit 文档中说:

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.

看来 isBatteryMonitoringEnabled 它只是让您能够通过询问其值(通过轮询)而不是观察它来读取电池。

关于swift - 观看操作系统 : Swift KVO for BatteryState is not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53541141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com