在Apple Watch上显示iPhone的电池

时间:2017-07-31 14:00:38

标签: ios swift apple-watch

我正试图在我的苹果手表应用程序的标签上显示iPhone的剩余电池电量。我尝试过使用WatchConnectivity并在iphone和Apple Watch之间发送消息,但是没有用。我有什么方法可以做到吗?

1 个答案:

答案 0 :(得分:2)

首先启用电池监控:

UIDevice.current.isBatteryMonitoringEnabled = true

然后你可以创建一个计算属性来返回电池电量:

var batteryLevel: Float {
    return UIDevice.current.batteryLevel
}

要监控设备电池电量,您可以为UIDeviceBatteryLevelDidChange通知添加观察者:

NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: .UIDeviceBatteryLevelDidChange, object: nil)
func batteryLevelDidChange(_ notification: Notification) {
    print(batteryLevel)
}

您还可以验证电池状态:

var batteryState: UIDeviceBatteryState {
    return UIDevice.current.batteryState
}
case .unknown   //  "The battery state for the device cannot be determined."
case .unplugged //  "The device is not plugged into power; the battery is discharging"
case .charging  //  "The device is plugged into power and the battery is less than 100% charged."
case .full      //   "The device is plugged into power and the battery is 100% charged."

并添加UIDeviceBatteryStateDidChange通知的观察者:

NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: .UIDeviceBatteryStateDidChange, object: nil)
func batteryStateDidChange(_ notification: Notification) {
    switch batteryState {
    case .unplugged, .unknown:
        print("not charging")
    case .charging, .full:
        print("charging or full")
    }
}

现在您拥有了有关电池的所有属性。把它们传递给手表吧!

希望这有帮助。