How can I read the status of the battery on my MacBookPro from my own application?
Googling has so far only revealed APIs for device drivers to handle power events - there's nothing about user-land processes accessing this information.
thanks.
The Battery Status API, more often referred to as the Battery API, provides information about the system's battery charge level and lets you be notified by events that are sent when the battery level or charging status change.
To view your battery's condition, choose Apple menu > System Preferences, click Battery , then click Battery again. In the lower right corner, click Battery Health.
Xcode 11 • Swift 5.1 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.
If you're looking for a quick way to query it from the command line, you'll find the pmset command helpful. To query the battery status, specifically, use:
$ pmset -g batt
You'll want to use IOKit for this, specifically the IOPowerSources functions. You can use IOPSCopyPowerSourcesInfo()
to get a blob, and IOPSCopyPowerSourcesList()
to then extract a CFArray out of that, listing the power sources. Then use IOPSGetPowerSourceDescription()
to pull out a dictionary (see IOPSKeys.h for the contents of the dictionary).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With