uidevicebatterystatedidchangenotification not working sometimes

痴心易碎 提交于 2020-02-25 04:39:07

问题


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 NSNotifications 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!