在Apple Watch上显示iPhone的电池
问题描述:
我正在尝试在我的Apple Watch应用程序的标签上显示iPhone的剩余电池电量。我试过使用WatchConnectivity并在iPhone和Apple Watch之间发送消息,但没有奏效。有什么办法可以做到吗?在Apple Watch上显示iPhone的电池
答
首先只是使电池监测:
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")
}
}
现在,你有你需要的关于你的电池的所有属性。只要通过他们的手表!
希望这会有所帮助。
请告诉我们您尝试了什么以及您遇到了什么错误。您确实应该使用'WatchConnectivity'框架与Watch进行iPhone通信。 –