uidevicebatterystatedidchangenotification 有时不工作

uidevicebatterystatedidchangenotification not working sometimes

我正在尝试检查设备的充电端口是否正常工作。 有两种情况—— 一种。当充电线已经插入时。 b.一段时间后插入充电线时。

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

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

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

有些人已将其标记为重复。因此,对于您有用的信息,这不是一个完全重复的问题,因为在这里我应用了某种方法来解决一个对我不起作用的问题.. AT ALL!!与我的问题类似的问题中提供的解决方案对我不起作用,因为我已经尝试过了。

你应该在 Object 设备上收听

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