Swift – Battery level and charger status

offer the batteryState in the class:

UIDevice.current.batteryState

You cannot read the batteryState directly, you need first to enable the :

UIDevice.current.isBatteryMonitoringEnabled = true

As Apple said:

Enable monitoring if your app needs to be notified of changes to the state, or if you want to check the charge level.

The default value of this property is NO, which:

  • Disables the posting of battery-related notifications
  • Disables the ability to read battery charge level and battery state
Setting this to true enable you to get all of these statuses:
public enum BatteryState : Int {
    case unknown   // called if the  is not enabled
    case  // without charger attached
    case charging  // with charger attached
    case       // at 100%
}

Here a simple function to read all these values:

func batteryStatus() {
  UIDevice.current.isBatteryMonitoringEnabled = true

  switch UIDevice.current.batteryState {
    case .unknown:
      print("BATTERY: UNKNOWN!")
    case .charging:
      print("BATTERY: charging...")
    case .full:
      print("BATTERY: full")
    case .unplugged:
      print("BATTERY: unplugged...")
  }
}

If you want also to know the battery level, you can use .

The battery level is a range from 0.0 (fully discharged) to 1.0 (100% charged).  This property become -1.0 if the battery monitor is not enabled.

print("BATTERY level: \(UIDevice.current.batteryLevel)")

that’s all.