Andrew M Andrew M - 1 year ago 106
Objective-C Question

Mac - Get Battery/Charging Status (Plugged in or not)

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:

  1. Polling interval on battery Polling

  2. interval while charging

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.

Answer Source

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.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download