我正在尝试获取项目中电池的状态,并在设备正在充电时将变量设置为true。我现在面临的问题是,无论是否收费,变量都不会更改。这是我的代码。
var chargingStatus: Bool? = false
func declaration() {
UIDevice.current.isBatteryMonitoringEnabled = true
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: UIDevice.batteryStateDidChangeNotification, object: nil)
}
@objc func batteryStateDidChange(_ notification: Notification) {
print("BATTERY STATE \(batteryState)")
switch batteryState {
case .unplugged, .unknown:
chargingStatus = false
case .charging:
chargingStatus = true
case .full:
chargingStatus = false
print("charging or full")
}
}
答案 0 :(得分:1)
您必须使用电池状态通知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%, ...)
}