我有这个密码:
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;
}
)
))
我试图从这个闭包中得到“正在充电”的值。我该怎么做?
我是新来的斯威夫特,所以任何帮助都将不胜感激。
提前谢谢!
最佳答案
根据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)
}
}
}
输出示例:
内部电池正在充电:错误
关于swift - 从IOPSCopyPowerSourcesInfo()中提取值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43953132/