Created
August 7, 2018 05:34
-
-
Save JayachandraA/c341554bd40d53b26699d5e375cd650f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
First just enable battery monitoring: | |
UIDevice.current.isBatteryMonitoringEnabled = true | |
Then you can create a computed property to return the battery level: | |
var batteryLevel: Float { | |
return UIDevice.current.batteryLevel | |
} | |
To monitor your device battery level you can add an observer for the UIDeviceBatteryLevelDidChange notification: | |
NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: .UIDeviceBatteryLevelDidChange, object: nil) | |
func batteryLevelDidChange(_ notification: Notification) { | |
print(batteryLevel) | |
} | |
You can also verify the battery state: | |
var batteryState: UIDeviceBatteryState { | |
return 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 UIDeviceBatteryStateDidChange notification: | |
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: .UIDeviceBatteryStateDidChange, object: nil) | |
func batteryStateDidChange(_ notification: Notification) { | |
switch batteryState { | |
case .unplugged, .unknown: | |
print("not charging") | |
case .charging, .full: | |
print("charging or full") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment