swift - 从 IOPSCopyPowerSourcesInfo() swift 中提取值

标签 swift iokit

我有这个代码:

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 的新手,如有任何帮助,我们将不胜感激。

提前致谢!

最佳答案

根据 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

关于swift - 从 IOPSCopyPowerSourcesInfo() swift 中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43953132/

相关文章:

macos - 您可以跟踪 MacOS 上进程的 I/O 事件吗?

macos - 带kIOReturnNoResources/0xe00002be的IOCreatePlugInInterfaceForService失败

cocoa - 如何在 Mac OS cocoa 中获取已安装 USB 设备的设备 ID、供应商 ID 和产品 ID

ios - 创建一个 UIProgressView 在 3 秒内从 0.0(空)到 1.0(满)

swift - ReactiveCocoa - 具有一般错误处理功能的信号生成器序列

ios - 今天,扩展 View 在 View 出现后会重新调整自身。 iOS swift

macos - 在 OS X 上以编程方式禁用环境光传感器屏幕变暗

c++ - MAC 中的 HID 设备接口(interface)

java - 如何在应用端添加fcm通知声音

ios - FBLogin libc++abi.dylib : terminating with uncaught exception of type NSException