从 IOPSCopyPowerSourcesInfo() 中提取值 swift

extracting value from IOPSCopyPowerSourcesInfo() swift

我有这个代码:

var source =  IOPSCopyPowerSourcesInfo()
print(source)

当我运行它时,它returns这个:

Optional(Swift.Unmanaged<Swift.AnyObject>(_value: <__NSCFArray 0x60800026f4c0>(
{
    "Battery Provides Time Remaining" = 1;
    BatteryHealth = Good;
    Current = "-1756";
    "Current Capacity" = 56;
    DesignCycleCount = 1000;
    "Hardware Serial Number" = C0143160D1JF90MAU;
    "Is Charging" = 0;
    "Is Present" = 1;
    "Max Capacity" = 100;
    Name = "InternalBattery-0";
    "Power Source ID" = 4063331;
    "Power Source State" = "Battery Power";
    "Time to Empty" = 117;
    "Time to Full Charge" = 0;
    "Transport Type" = Internal;
    Type = InternalBattery;
}
)
))

我正在尝试从此闭包中获取 "Is Charging" 值。我该怎么做?

我是 Swift 的新手,如有任何帮助,我们将不胜感激。

提前致谢!

根据 IOPSCopyPowerSourcesInfo 的文档,

Clients should not directly access data in the returned CFTypeRef - they should use the accessor functions IOPSCopyPowerSourcesList and IOPSGetPowerSourceDescription, instead.

这是一个例子:

import IOKit.ps

let psInfo = IOPSCopyPowerSourcesInfo().takeRetainedValue()
let psList = IOPSCopyPowerSourcesList(psInfo).takeRetainedValue() as [CFTypeRef]

for ps in psList {
    if let psDesc = IOPSGetPowerSourceDescription(psInfo, ps).takeUnretainedValue() as? [String: Any] {
        if let type = psDesc[kIOPSTypeKey] as? String,
            let isCharging = (psDesc[kIOPSIsChargingKey] as? Bool) {
            print(type, "is charging:", isCharging)
        }
    }
}

输出示例:

InternalBattery is charging: false