简体   繁体   English

迅速观察电池电量不足

[英]Observe battery out of charge, Swift

I want to execute some code when iPhone battery iPhone run out of battery. 我想在iPhone电池iPhone耗尽电池时执行一些代码。

Will func applicationWillTerminate(_ application: UIApplication) { be called? 请问func applicationWillTerminate(_ application: UIApplication) {被叫? If no then does exist any other way to track this? 如果没有那么存在任何其他方式来跟踪这个? Thanks in advance. 提前致谢。

There is no support for this instead you have to decide when the battery level is so low that you need to run your code. 没有对此的支持,您必须决定何时电池电量太低以至于您需要运行代码。

What you can do is listen to the notification batteryLevelDidChangeNotification which is done by activating monitoring see isBatteryMonitoringEnabled 您可以做的是通过激活监控来监听通知batteryLevelDidChangeNotification ,请参阅isBatteryMonitoringEnabled

Like mentioned in the documentation the notifications are sent no more than once per minute so you have to determine a battery level that is low enough to be considered as almost depleted and then execute the code. 如文档中所述,通知每分钟发送的次数不超过一次,因此您必须确定一个足够低的电池电量,以便将其视为几乎耗尽,然后执行代码。

I have no idea what this could be, from personal experience I have seen my phones stay alive a long time on values under 5% but also seen them die shortly after going below 10% 我不知道这可能是什么,从个人经验来看,我看到我的手机长时间保持在5%以下的价值,但也看到它们在低于10%后不久就死了

You can use the following code snippet: 您可以使用以下代码段:

    func startObservingBatteryDrainage(){
        if UIDevice.current.isBatteryMonitoringEnabled && (UIDevice.current.batteryState == .unplugged || UIDevice.current.batteryState == .unknown){
            if UIDevice.current.batteryLevel < 0.1{
                NotificationCenter.default.addObserver(self, selector: #selector(funcWhenBatteryIsAlmostDrained), name: UIDevice.batteryLevelDidChangeNotification, object: nil)
            }
        }
    }

    @objc func funcWhenBatteryIsAlmostDrained(){
        //do stuff

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM