问题
What I wanted to do is take a log on battery percentage. I know the equivalent in linux is sysctl(hw.acpi.battery.life). However when I went through the man of sysctl in mac os x I did not find the equivalent code to find it. Can some one point out how to do this using objective c. I can call sysctlbyname but that doesn't have this as input in its struct. Kindly help me please
回答1:
Try using IOKit and 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. Finally you can use the IOPSGetPowerSourceDescription() to grab the dictionary.
If you can use the command line, you can use the pmset command
Like so:
$ pmset -g
回答2:
you may use ioreg on the command line as well. For example:
ioreg -l -w0 |grep CurrentCapacity
gives you the current battery status, which may be compared to the max capacity:
ioreg -l -w0 |grep MaxCapacity
回答3:
Another way to get some more info on battery status is to use NSTask to execute the system_profiler command with SPPowerDataType as the argument. On my Mac, it gives me the following results :
Battery Information:
Model Information:
Serial Number: W01396THJD3LA
Manufacturer: SMP
Device Name: bq20z451
Pack Lot Code: 0
PCB Lot Code: 0
Firmware Version: 201
Hardware Revision: 000a
Cell Revision: 165
Charge Information:
Charge Remaining (mAh): 5013
Fully Charged: Yes
Charging: No
Full Charge Capacity (mAh): 5086
Health Information:
Cycle Count: 72
Condition: Normal
Battery Installed: Yes
Amperage (mA): -300
Voltage (mV): 12303
To retrieve what you specifically, you could either parse the appropriate lines, or generate a plist with this command:
$ system_profiler SPPowerDataType -xml > BatteryInfo.plist
This would make it easier to retrieve the values, based on specific keys.
来源:https://stackoverflow.com/questions/1432792/how-to-get-the-battery-life-of-mac-os-x-macbooks-programatically