2

So far I have the code snippet: charging = IOPSGetTimeRemainingEstimate().isEqual(to: kIOPSTimeRemainingUnlimited), which returns true or false depending on whether the computer is charging or not. I want to monitor this value for updates so that it runs a script on change. I am new to Swift and any help would be appreciated. Thanks!

asportnoy
  • 2,218
  • 2
  • 17
  • 31

1 Answers1

0

You can get the charging state with:

import IOKit.ps

let info = IOPSCopyPowerSourcesInfo().takeRetainedValue()
let sources = IOPSCopyPowerSourcesList(info).takeRetainedValue() as [CFTypeRef]
if let batterySource = sources.first {
    let pSource = IOPSGetPowerSourceDescription(info, batterySource).takeUnretainedValue() as NSDictionary
    let isCharging = pSource[kIOPSIsChargingKey] as! Int // 1 = charging, 0 = not charging
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Sorry, I wasn't very clear, but I want to monitor this value for changes. I want to be able to run a function when it changes. Thank you for your help though. – asportnoy Aug 05 '17 at 18:45
  • *Monitoring* can be also a simple timer. However there is an API `IOPSNotificationCreateRunLoopSource` to register for a notification about changes – vadian Aug 05 '17 at 18:50