代码之家  ›  专栏  ›  技术社区  ›  Abhishek Thapliyal

观察操作系统:batterystate的swift kvo不工作

  •  2
  • Abhishek Thapliyal  · 技术社区  · 7 年前

    我想监视电池状态,所以我为电池状态添加了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
    }
    

    但当插入/拔出插头充电器时,它不会被调用。 有什么许可证吗?或者我遗漏了什么?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Andrea    7 年前

    据我在文档中看到的,并没有清楚地说明这个属性是kvo兼容的。
    在watchkit文档中,他们说:

    如果启用了电池监测,则此属性设置为一个值 介于0.0(0%充电)和1.0(100%充电)之间。当电池状态 属性设置为wkInterfaceDeviceBatteryState.Unknown(例如, 禁用电池监测时,该值为-1.0。

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