Getting Battery Status and Battery Level

suggest change

This is Swift 3. batteryLevel stays -1 until battery monitoring is enabled, and the Simulator often still reports -1. A selector spelled batteryStateDidChange: does not match batteryStateDidChange(notification:).

override func viewDidLoad() {
    super.viewDidLoad()
    UIDevice.current.isBatteryMonitoringEnabled = true
    NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange(notification:)), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange(notification:)), name: NSNotification.Name.UIDeviceBatteryLevelDidChange, object: nil)

    // Stuff...
}

func batteryStateDidChange(notification: NSNotification) {
    // The state did change: plugged, unplugged, full charge...
}

func batteryLevelDidChange(notification: NSNotification) {
    let batteryLevel = UIDevice.current.batteryLevel
    if batteryLevel < 0.0 {
        print("-1.0 means monitoring is off or the battery state is unknown")
        return
    }

    print("Battery Level : \(batteryLevel * 100)%")
    // The battery's level did change (98%, 99%, ...)
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents