【问题标题】:Displaying iPhone's battery on an Apple Watch在 Apple Watch 上显示 iPhone 的电池
【发布时间】:2017-07-31 14:00:38
【问题描述】:

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

【问题讨论】:

  • 请向我们展示您尝试过的内容以及遇到的错误。您确实应该使用 WatchConnectivity 框架从 Watch 与 iPhone 进行通信。

标签: ios swift apple-watch


【解决方案1】:

首先启用电池监控:

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

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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    相关资源
    最近更新 更多