uidevicebatterystatedidchangenotification有时不工作

时间:2017-09-07 12:31:13

标签: ios swift nsnotificationcenter battery uidevice

我正在尝试检查设备的充电端口是否正常工作。 有两种情况 - 一个。当充电电缆已插入时。 湾当充电电缆在一段时间后插入时。

对于案例a,在viewDidLoad()上我检查了启用batteryStateMonitoring并检查了电池的当前状态。 - 它总是有效。

对于案例b,我尝试使用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
        }
    }

每次都不会触发NSNotification UIDeviceBatteryStateDidChangeNotification。它并不是每次都调用选择器方法。在插入电缆的10次中,它仅成功响应2次。即使设备开始充电。

有些人将其标记为重复。所以对于你的亲切信息,这不是一个完全重复的问题,因为在这里我已经应用了某些方法来解决一个对我不起作用的问题。所有!在与我的问题类似的问题中提供的解决方案对我来说是合适的,因为我已经尝试过了。

1 个答案:

答案 0 :(得分:1)

你应该听对象设备

        NotificationCenter.default.addObserver(self,selector: #selector(ViewController.monitorBatteryStatus), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: UIDevice.current)