【问题标题】:extracting value from IOPSCopyPowerSourcesInfo() swift快速从 IOPSCopyPowerSourcesInfo() 中提取值
【发布时间】:2017-05-13 12:24:56
【问题描述】:

我有这个代码:

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;
}
)
))

我正在尝试从此关闭中获取“正在充电”值。我该怎么做?

我是 Swift 新手,因此我们将不胜感激。

提前致谢!

【问题讨论】:

  • source 作为数组,然后第一个元素作为 Dictionary,然后 element["Is Charging"] ?
  • @Larme 你能扩展一下吗?

标签: swift iokit


【解决方案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 正在充电:假

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 2021-11-05
    相关资源
    最近更新 更多