在 Apple Watch 上显示 iPhone 的电池

Displaying iPhone's battery on an Apple Watch

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

首先启用电池监控:

UIDevice.current.isBatteryMonitoringEnabled = true

然后你可以创建一个属性到return的计算电池电量:

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

现在您拥有了电池所需的所有属性。只需将它们传递给手表即可!

希望对您有所帮助。