Polling battery percentage on MacOs


This is an extension of my last post which covered polling battery percentage within iOS:

https://nsaxelby.com/2018/05/06/polling-battery-percentage-on-iphone/

This post is describes how to do it in MacOs

Introduction:

This post explores how to poll for the battery percentage on a MacOsx device. My MacOs device that I’m building on is a High Sierra MacBook Air ( 2014 ).

Implementation:

Fortunately querying the battery percentage on a MacOs device is much easier than on a iOS. You don’t have to worry about all of the ‘background capabilities’ and modes requires for the iOS implementation. We will use the same NSTimer to poll within the app every X seconds, but we will use IOPowerSources.h  within IOKit  to obtain the battery percentage.

Step 1:

Within your MacOs application AppDelegate.h  ( or wherever you want to put it ) import the IOKit ‘s IOPowerSources :

Within your AppDelegate.m create the method that will get the battery percentage and do whatever you want to do with the percentage, add the following method:

Step 2:

Hook up your method of a NSTimer by putting the following code in your applicationDidFinishLaunching  within the AppDelegate.m :

If you fire up your app, you will see the the debug output look something like this:

 

Full git source code sample application here:

https://github.com/nsaxelby/MacOsBatteryMonitorApp