iOS Battery Level
First we need enable battery monitoring to get Battery Level & Battery Status
Battery level ranges from 0.0 (fully discharged) to 1.0 (100% charged)
To get the Battery Level
You can add observer to monitor Battery Level continuously.
NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: UIDevice.batteryLevelDidChangeNotification, object: nil)
//MARK:- Get Battery Level
@objc func batteryLevelDidChange(_ notification: Notification) {
print("\(Int(batteryLevel * 100))%")
}
Ref: Apple Document - Battery Level
You can also verify the battery power state of the device
Overview:
Enumeration
constants are used by the batteryState property
-
case .unknown
The battery state for the device cannot be determined
case .unplugged
The battery is discharging
-
case .charging
The device is plugged into power & the battery is less than 100% charged
case . full
The device is plugged into power and the battery is 100% charged
You can add observer to monitor Battery State continuously.
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: UIDevice.batteryStateDidChangeNotification, object: nil)
//MARK:- Get Battery State
@objc func batteryStateDidChange(_ notification: Notification) {
switch batteryState {
case .unplugged, .unknown:
print("Not charging")
case .charging:
print("Charging")
case .full:
print("Full")
@unknown default:
print("Nothing")
}
}
Ref: Apple Document - Battery State
Sample:
Let's grow together 🌱
Cheers 🍻