-2
我正在嘗試在我的Apple Watch應用程序的標籤上顯示iPhone的剩餘電池電量。我試過使用WatchConnectivity並在iPhone和Apple Watch之間發送消息,但沒有奏效。有什麼辦法可以做到嗎?在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通信。 –