如何使用swift监控电池电量和状态变化 [英] How to monitor battery level and state changes using swift
问题描述
所以,我正在试图弄清楚如何监控iOS设备中的电池电量和状态变化。
So, I'm trying to figure out how to monitor the battery level and state changes in iOS devices.
到目前为止,我已经确定如何获得目前的电池电量,但无法弄清楚如何获得状态或如何监控任何变化,所以我可以弹出一个对话框(或通知,但我认为我无法在后台监控这个...所以...) 100%收费。
So far I've determined how to get the current battery level, but can't figure out how to get the state or how to monitor any changes so I can pop a dialog (or notification, but I assume I can't monitor this in the background anyway so...) when 100% charged.
这是我到目前为止:
@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)
}
}
任何帮助在这里将不胜感激!谢谢!
Any assistance here would be greatly appreciated! Thanks!
推荐答案
您可以使用电池状态通知 UIDeviceBatteryStateDidChangeNotification
和 UIDeviceBatteryLevelDidChangeNotification
在状态发生变化时收到通知:
You can use the battery state notification UIDeviceBatteryStateDidChangeNotification
and UIDeviceBatteryLevelDidChangeNotification
to be notified when its state changed:
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监控电池电量和状态变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!