如何使用swift监视电池电量和状态变化
所以,我想弄清楚如何监控iOS设备的电池电量和状态变化。
到目前为止,我已经决定如何获得当前的电池电量,但不知道如何获取状态或如何监视任何更改,以便popup对话框(或通知,但我认为我无法监视在背景无论如何,所以…)当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) } }
任何援助在这里将不胜感激! 谢谢!
您可以使用电池状态通知UIDeviceBatteryStateDidChangeNotification
和UIDeviceBatteryLevelDidChangeNotification
在状态更改时通知:
override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryStateDidChange:", name: UIDeviceBatteryStateDidChangeNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryLevelDidChange:", name: UIDeviceBatteryLevelDidChangeNotification, object: nil) // Stuff... } func batteryStateDidChange(notification: NSNotification){ // The stage did change: plugged, unplugged, full charge... } func batteryLevelDidChange(notification: NSNotification){ // The battery's level did change (98%, 99%, ...) }
这里是实现Swift 3.0的代码@tbaranes的新方法
NotificationCenter.default.addObserver(self, selector: Selector(("batteryStateDidChange:")), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: Selector(("batteryLevelDidChange:")), name: NSNotification.Name.UIDeviceBatteryLevelDidChange, object: nil)
现在通过UIDevice类有了新的方法:
获取设备电池状态
var batteryLevel: Float
设备的电池电量。
var isBatteryMonitoringEnabled: Bool
一个布尔值,指示电池监视是否启用(true)或不(false)。
var batteryState: UIDeviceBatteryState
设备的电池状态。
使用UIDeviceBatteryState
具有以下值:
case unknown
设备的电池状态无法确定。
case unplugged
该设备未插入电源; 电池正在放电。
case charging
该设备插入电源,电池less于100%充电。
case full
该设备插入电源,电池100%充电。