Swift – Battery level and charger status

Apple offer the batteryState in the UIDevice class:

UIDevice.current.batteryState

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

UIDevice.current.isBatteryMonitoringEnabled = true

As Apple said:

Enable battery monitoring if your app needs to be notified of changes to the battery state, or if you want to check the battery 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 monitor is not enabled
    case unplugged // without charger attached
    case charging  // with charger attached
    case full      // 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 batteryLevel.

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.

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.