swift:等到电源发生变化(mac)

时间:2017-08-05 16:46:48

标签: swift xcode macos iokit

到目前为止,我有代码片段: charging = IOPSGetTimeRemainingEstimate().isEqual(to: kIOPSTimeRemainingUnlimited),根据计算机是否正在充电,返回true或false。我想监视此值以进行更新,以便在更改时运行脚本。我是Swift的新手,任何帮助都会受到赞赏。谢谢!

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式获得充电状态:

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
}