问题
I am trying to check if device's charging port is working fine. There are two scenarios - a. when the charging cable is already plugged in. b. when the charging cable is plugged in after sometime.
For case a, on viewDidLoad()
I checked for enable batteryStateMonitoring
and checked the current state of the battery. - It always works.
For case b, I tried using NSNotification
s UIDeviceBatteryStateDidChangeNotification
override func viewDidLoad() {
UIDevice.current.isBatteryMonitoringEnabled = true
self.checkForCharging()
}
func checkForCharging() {
if UIDevice.current.batteryState == .full || UIDevice.current.batteryState == .charging {
self.updateUIForChargingTest()
} else {
NotificationCenter.default.addObserver(self,selector: #selector(ViewController.monitorBatteryStatus), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil)
}
}
func monitorBatteryStatus() {
if self.MonitorBatteryStatus(state: UIDevice.current.batteryState) == true {
self.updateUIForChargingTest()
}
else {
print("Device Battery State Unknown")
}
}
func MonitorBatteryStatus(state : UIDeviceBatteryState) -> Bool {
switch state {
case UIDeviceBatteryState.charging:
return true
case UIDeviceBatteryState.full:
return true
default:
return false
}
}
The NSNotification
UIDeviceBatteryStateDidChangeNotification
is not triggered everytime. It doesn't call the selector method everytime. Out of 10 times I plug-in the cable, it successfully responds only 2 times. Even when device begins charging.
Some people have marked it as duplicate. So for you kind information, this isnt an exact duplicate question because here I have applied certain approach to a problem which isnot working for me..AT ALL!! Solutions provided in the questions similar to my question are nt working for me, Since i have already tried them.
回答1:
You should listen on Object device
NotificationCenter.default.addObserver(self,selector: #selector(ViewController.monitorBatteryStatus), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: UIDevice.current)
来源:https://stackoverflow.com/questions/46096439/uidevicebatterystatedidchangenotification-not-working-sometimes