【发布时间】:2022-02-27 13:23:30
【问题描述】:
所以,我想弄清楚如何监控 iOS 设备中的电池电量和状态变化。
到目前为止,我已确定如何获取当前电池电量,但不知道如何获取状态或如何监控任何更改,因此我可以弹出一个对话框(或通知,但我想我可以'无论如何都不要在后台监控这个,所以......)当 100% 充电时。
这是我目前所拥有的:
@IBOutlet var BatteryLevelLabel: UILabel!
@IBOutlet var BatteryStateLabel: UILabel!
// function to return the devices battery level
func batteryLevel()-> Float {
return UIDevice.currentDevice().batteryLevel
}
// function to return the devices battery state (Unknown, Unplugged, Charging, or Full)
func batteryState()-> UIDeviceBatteryState {
return UIDevice.currentDevice().batteryState
}
override func viewDidLoad() {
super.viewDidLoad()
let currentBatteryLevel = batteryLevel()
// enables the tracking of the devices battery level
UIDevice.currentDevice().batteryMonitoringEnabled = true
// shows the battery level on labels
BatteryLevelLabel.text = "\(batteryLevel() * 100)%)"
BatteryStateLabel.text = "\(batteryState())"
print("Device Battery Level is: \(batteryLevel()) and the state is \(batteryState())")
// shows alert when battery is 100% (1.0)
if currentBatteryLevel == 1.0{
let chargedAlert = UIAlertController(title: "Battery Charged", message: "Your battery is 100% charged.", preferredStyle: UIAlertControllerStyle.Alert)
chargedAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
presentViewController(chargedAlert, animated: true, completion: nil)
}
}
这里的任何帮助将不胜感激!谢谢!
【问题讨论】: