I'm building a Mac OSX app that needs to poll a server every minute, or even less if the user wishes. Unfortunately the service doesn't support push...
Anyways, I would like to provide two options to the user:
How would I get the state of the charger in Objective C? I don't really care about the actual percentage, only if the laptop is plugged in or not. Obviously, this doesn't matter for desktops, so hopefully there is a solution that works for laptops and desktops.
Have a look at the IOPowerSources API.
First call IOPSCopyPowerSourcesInfo()
, then IOPSCopyPowerSourcesList()
to get a list of all available power sources. IOPSGetPowerSourceDescription()
will return a dictionary with information about a particular power source. According to the documentation, the key kIOPSPowerSourceStateKey
describes "the current source of power. kIOPSBatteryPowerValue
indicates power source is drawing internal power; kIOPSACPowerValue
indicates power source is connected to an external power source."
You can also set up a notification when the power sources change with IOPSNotificationCreateRunLoopSource()
.
(NB: I haven't tested any of this, just looked at the documentation.)
Although this question does already have an accepted answer which led me to my solution, it was painful to click through lots and lots of broken links.
Here is my solution:
IOKit.framework
#import <IOKit/ps/IOPowerSources.h>
Code:
CFTimeInterval timeRemaining = IOPSGetTimeRemainingEstimate();
if (timeRemaining == kIOPSTimeRemainingUnlimited) {
// connected to outlet
} else if (timeRemaining == kIOPSTimeRemainingUnknown){
// time remaining unknown (recently unplugged)
} else if ((timeRemaining / 60) < 30){
// less than 30 minutes remaining
}
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