Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 684
Andrew M Avatar asked Apr 22 '11 00:04

Andrew M


2 Answers

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

like image 121
Ole Begemann Avatar answered Oct 06 '22 01:10

Ole Begemann


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:

  1. Add IOKit.framework
  2. Import #import <IOKit/ps/IOPowerSources.h>
  3. 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
    }
    
like image 31
Git.Coach Avatar answered Oct 06 '22 01:10

Git.Coach