Check Battery Level iOS Swift
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)
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.
@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")
}
}
Check if battery charging status changes in real time Swift
Basically you did everything to display the current status, now you need to add something that is notified, or checks regularly for said status.
In this case, I believe the best way would be to register to the batteryStateDidChangeNotification
notification, which is only sent by the system when isBatteryMonitoringEnabled
is set to true, as you did in the viewDidLoad
I think adding
NotificationCenter.default.addObserver(
self,
selector: #selector(batteryStatus),
name: UIDevice.batteryStateDidChangeNotification,
object: nil
)
Should do the trick. In the viewDidLoad
for instance.
Swift 3 Xcode: How to display battery levels as an integer?
Try this instead:
func someFunction() {
self.infoLabel.text = String(format: "%.0f%%", batteryLevel * 100)
}
For future reference, all string format specifiers are listed here.
How to monitor battery level and state changes using swift
You can use the battery state notification UIDeviceBatteryStateDidChangeNotification
and UIDeviceBatteryLevelDidChangeNotification
to be notified when its state changed:
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryStateDidChange:", name: UIDeviceBatteryStateDidChangeNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryLevelDidChange:", name: UIDeviceBatteryLevelDidChangeNotification, object: nil)
// Stuff...
}
func batteryStateDidChange(notification: NSNotification){
// The stage did change: plugged, unplugged, full charge...
}
func batteryLevelDidChange(notification: NSNotification){
// The battery's level did change (98%, 99%, ...)
}
how to access device battery level from lock screen
I went through this this tutorial
and this seems to be working perfectly. I made only one change, that is, in info.plist file I added a new property Application does not run in background
& gave it a value YES
.
Related Topics
How to Update a Coredata Entry That Has Already Been Saved in Swift
Uisearchbar Presented by Uisearchcontroller in Table Header View Animates Too Far When Active
Control Cursor Position in Uitextfield
How to Dynamically Change the Font Size in Auto Layout iOS
Including Custom Data into iOS Crash Dumps
Lazy Loading Data in iOS Carplay
How to Add Images for Different Screen Size from Assets.Xcassets in Xcode 8
Optional Binding with Try? and As? Still Produces an Optional Type
Uiimagejpegrepresentation Returns Nil
How to Rotate Orientation Programmatically in Swift
Example for Login Screen Modally Based on Storyboard
What Does Deployment Target Mean
Why the Skstorereviewcontroller Does Not Let Me Submit a Review
Type 'Viewcontroller' Does Not Conform to Protocol 'Uitableviewdatasource'
Swift Error:Signal Sigabrt How to Solve It
Making a Button Persistent Across All View Controllers
How to Set an Nsdate Object to Midnight
Cannot Put a Google Maps Gmsmapview in a Subview of Main Main View