我有这段代码:
var source = IOPSCopyPowerSourcesInfo()
print(source)
当我运行它时,它会返回:
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的新手,所以任何帮助都会受到赞赏。
提前致谢!
答案 0 :(得分:1)
根据IOPSCopyPowerSourcesInfo
的文件,
客户端不应直接访问返回的CFTypeRef中的数据 - 它们应该使用访问器函数IOPSCopyPowerSourcesList和IOPSGetPowerSourceDescription。
以下是一个例子:
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