How can I get battery level and state (plugged in, discharging, charging, etc) in iOS?


In this post we will be seeing how to get the battery state in iOS.

So let’s get started.

Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “BatteryState”

Step 2 − Open Main.storyboard and add two label as shown below. On this label we will show battery status.

Step 3 − Enable the battery state monitoring, using the following code. You can put this code in viewDidLoad of ViewController

UIDevice.current.isBatteryMonitoringEnabled = true

Step 4 − Declare a variable to hold the battery state. We will name this variable batteryState. From this variable we are returning UIDevice.current.batteryState, that would give us the current battery state

var batteryState: UIDevice.BatteryState {
   return UIDevice.current.batteryState
}

Step 5 − You will need to add the observer for battery state change notifications. This notification is sent by iOS whenever the battery state changes. You can add the observer in viewDidLoad as shown below

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

We have added the observer, the function batteryLevelDidChange will get called whenever the battery level changes.

Step 6 − Handle the battery level changes in batteryLevelDidChange method. Define the method as follows

@objc func batteryLevelDidChange() {
   updateBatteryStateLabel()
}
func updateBatteryStateLabel() {
   var status = "Unknown"
   switch batteryState {
      case .charging:
      status = "Charging"
      case .unknown:
      status = "Unknown"
      case .unplugged:
      status = "Unplugged"
      case .full:
      status = "Full"
   }
   DispatchQueue.main.async {
      self.batteryStateLabel.text = "Battery State: \(status)"
   }
}

Here we have defined updateBatteryStateLabel function to update the label. This function we are calling from our observer function i.e. batteryLevelDidChange. Function updateBatteryStateLabel should be called from viewDidLoad as well to show the initial battery state. Our viewDidLoad looks like following after doing all of this

override func viewDidLoad() {
   super.viewDidLoad()
   UIDevice.current.isBatteryMonitoringEnabled = true
   NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: UIDevice.batteryLevelDidChangeNotification, object: nil)
   updateBatteryStateLabel()
}

Run the code on device, based on the battery state you will see different states as depicted in picture below.

Updated on: 11-Sep-2019

523 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements