Xcode 11 • Swift 5.1
First just enable battery monitoring:
UIDevice.current.isBatteryMonitoringEnabled = true
Then you can create a computed property to return the battery level:
Battery level ranges from 0.0 (fully discharged) to 1.0 (100%
charged). Before accessing this property, ensure that battery
monitoring is enabled. If battery monitoring is not enabled, battery
state is UIDevice.BatteryState.unknown and the value of this property
is –1.0.
var batteryLevel: Float { UIDevice.current.batteryLevel }
To monitor your device battery level you can add an observer for the UIDevice.batteryLevelDidChangeNotification
:
NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: UIDevice.batteryLevelDidChangeNotification, object: nil)
@objc func batteryLevelDidChange(_ notification: Notification) {
print(batteryLevel)
}
You can also verify the battery state:
var batteryState: UIDevice.BatteryState { UIDevice.current.batteryState }
case .unknown // "The battery state for the device cannot be determined."
case .unplugged // "The device is not plugged into power; the battery is discharging"
case .charging // "The device is plugged into power and the battery is less than 100% charged."
case .full // "The device is plugged into power and the battery is 100% charged."
and add an observer for UIDevice.batteryStateDidChangeNotification
:
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: UIDevice.batteryStateDidChangeNotification, object: nil)
@objc func batteryStateDidChange(_ notification: Notification) {
switch batteryState {
case .unplugged, .unknown:
print("not charging")
case .charging, .full:
print("charging or full")
}
}