Example
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: Selector(("batteryStateDidChange:")), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: Selector(("batteryLevelDidChange:")), name: NSNotification.Name.UIDeviceBatteryLevelDidChange, object: nil)
// Stuff...
}
func batteryStateDidChange(notification: NSNotification){
// The stage did change: plugged, unplugged, full charge...
}
func batteryLevelDidChange(notification: NSNotification){
let batteryLevel = UIDevice.current.batteryLevel
if batteryLevel < 0.0 {
print(" -1.0 means battery state is UIDeviceBatteryStateUnknown")
return
}
print("Battery Level : \(batteryLevel * 100)%")
// The battery's level did change (98%, 99%, ...)
}