【问题标题】:How to monitor battery level and state changes using swift如何使用 swift 监控电池电量和状态变化
【发布时间】:2022-02-27 13:23:30
【问题描述】:

所以,我想弄清楚如何监控 iOS 设备中的电池电量和状态变化。

到目前为止,我已确定如何获取当前电池电量,但不知道如何获取状态或如何监控任何更改,因此我可以弹出一个对话框(或通知,但我想我可以'无论如何都不要在后台监控这个,所以......)当 100% 充电时。

这是我目前所拥有的:

@IBOutlet var BatteryLevelLabel: UILabel!
@IBOutlet var BatteryStateLabel: UILabel!

// function to return the devices battery level
    func batteryLevel()-> Float {
        return UIDevice.currentDevice().batteryLevel
    }

// function to return the devices battery state (Unknown, Unplugged, Charging, or Full)
    func batteryState()-> UIDeviceBatteryState {
        return UIDevice.currentDevice().batteryState
    }

override func viewDidLoad() {
        super.viewDidLoad()

         let currentBatteryLevel = batteryLevel()

        // enables the tracking of the devices battery level
        UIDevice.currentDevice().batteryMonitoringEnabled = true

        // shows the battery level on labels
        BatteryLevelLabel.text = "\(batteryLevel() * 100)%)"
        BatteryStateLabel.text = "\(batteryState())"
        print("Device Battery Level is: \(batteryLevel()) and the state is \(batteryState())")

// shows alert when battery is 100% (1.0)
        if currentBatteryLevel == 1.0{
            let chargedAlert = UIAlertController(title: "Battery Charged", message: "Your battery is 100% charged.", preferredStyle: UIAlertControllerStyle.Alert)

            chargedAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
                print("Handle Ok logic here")
            }))
            presentViewController(chargedAlert, animated: true, completion: nil)
        }

    }

这里的任何帮助将不胜感激!谢谢!

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您可以使用电池状态通知UIDeviceBatteryStateDidChangeNotificationUIDeviceBatteryLevelDidChangeNotification 在其状态更改时收到通知:

    override func viewDidLoad() {
        super.viewDidLoad()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryStateDidChange:", name: UIDeviceBatteryStateDidChangeNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryLevelDidChange:", name: UIDeviceBatteryLevelDidChangeNotification, object: nil)   
    
        // Stuff...
    }
    
    func batteryStateDidChange(notification: NSNotification){     
        // The stage did change: plugged, unplugged, full charge...
    }
    
    func batteryLevelDidChange(notification: NSNotification){     
       // The battery's level did change (98%, 99%, ...)
    }
    

    【讨论】:

    • 有相应的状态变化通知:UIDeviceBatteryStateDidChangeNotification
    • hmm,所以我将 NSNotificationCenter 行添加到我的 viewDidLoad() 并添加了 batteryStateDidChange 函数。然后将我的 BatteryLevelLabel.text = "(batteryLevel() * 100)%" 复制到这个新函数(假设它会随着电池充电而改变)并将警报代码也放在那里。在我的设备上运行应用程序,它的电量为 98%,但一直插着电源。充电到 99%,标签没有更新。充电到 100% 警报未触发。显然我做错了什么?
    • 只有在状态改变时才会触发此通知,这意味着不是消耗或恢复的每个百分比,而是说拔掉、充电、充满...如果您想收到每个百分比的通知,将UIDeviceBatteryStateDidChangeNotification 替换为UIDeviceBatteryLevelDidChangeNotification
    • 是的,就是这样!非常感谢!
    • 'UIDevice.currentDevice().batteryMonitoringEnabled = true'
      应该在添加观察者之前。在 swift 2 中,我只有在添加上述行后才会触发通知
    【解决方案2】:

    这是实现 @tbaranes 为 Swift 3.0 建议的代码的新方法

    NotificationCenter.default.addObserver(self, selector: Selector(("batteryStateDidChange:")), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil)
    NotificationCenter.default.addObserver(self, selector: Selector(("batteryLevelDidChange:")), name: NSNotification.Name.UIDeviceBatteryLevelDidChange, object: nil)
    

    【讨论】:

      【解决方案3】:

      现在有新方法通过UIDevice class:

      获取设备电池状态

      var batteryLevel: Float
      

      设备的电池电量。

      var isBatteryMonitoringEnabled: Bool
      

      一个布尔值,指示是否启用电池监控 (真)或不(假)。

      var batteryState: UIDeviceBatteryState
      

      设备的电池状态。

      UIDeviceBatteryState 具有以下值:

      case unknown
      

      无法确定设备的电池状态。

      case unplugged
      

      设备未插入电源;电池正在放电。

      case charging
      

      设备已插入电源且电池电量低于 100% 收费。

      case full
      

      设备已接通电源,电池已充电 100%。

      【讨论】:

        【解决方案4】:

        Swift 5 版本的解决方案:

        NotificationCenter.default.addObserver(self, selector: #selector(batteryLavelChanged), name: UIDevice.batteryLevelDidChangeNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(batteryStateChanged),name: UIDevice.batteryStateDidChangeNotification, object: nil)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多