使用 Swift 获取我的 MacBook 的电池状态

Fetch the battery status of my MacBook with Swift

我想设置一个 Playground 来获取我的 macbook 的电池状态。

我已经尝试过以下方法:

import Cocoa
import IOKit
import Foundation

var blob = IOPSCopyPowerSourcesInfo()

我目前收到如下错误

Use of unresolved identifier 'IOPSCopyPowerSourcesInfo'

它在 Playground 中不起作用,但在真实应用中有效。

我无法仅使用 Swift 和 import IOKit 访问 IOPowerSources.h 头文件,但是:我必须建立一个到 Objective-C.[=27 的桥梁=]

这是我的解决方案:

  1. IOKit.framework 添加到您的项目中(单击 Linked Frameworks and Libraries 中的 +

  2. 创建一个新的空 .m 文件,无论其名称如何。 Xcode 然后会询问它是否应该制作一个 "bridging header"。说是。

  3. 忽略.m文件。在 Xcode 刚刚创建的新 YOURAPPNAME-Bridging-Header.h 文件中,添加行 #import <IOKit/ps/IOPowerSources.h> (不要在 Swift 文件中添加 import IOKit )

  4. 您现在可以访问大多数 IOPowerSources 功能。

示例:

func getBatteryStatus() -> String {
    let timeRemaining: CFTimeInterval = IOPSGetTimeRemainingEstimate()
    if timeRemaining == -2.0 {
        return "Plugged"
    } else if timeRemaining == -1.0 {
        return "Recently unplugged"
    } else {
        let minutes = timeRemaining / 60
        return "Time remaining: \(minutes) minutes"
    }
}

let batteryStatus = getBatteryStatus()
print(batteryStatus)

注意:我无法访问像 kIOPSTimeRemainingUnlimitedkIOPSTimeRemainingUnknown 这样的常量,所以我使用了它们的原始值(-2.0 和 -1.0),但最好找到这些常量如果它们仍然存在于某处。

另一个例子IOPSCopyPowerSourcesInfo:

let blob = IOPSCopyPowerSourcesInfo()
let list = IOPSCopyPowerSourcesList(blob.takeRetainedValue())
print(list.takeRetainedValue())

结果:

(
{
"Battery Provides Time Remaining" = 1;
BatteryHealth = Good;
Current = 0;
"Current Capacity" = 98;
DesignCycleCount = 1000;
"Hardware Serial Number" = 1X234567XX8XX;
"Is Charged" = 1;
"Is Charging" = 0;
"Is Present" = 1;
"Max Capacity" = 100;
Name = "InternalBattery-0";
"Power Source State" = "AC Power";
"Time to Empty" = 0;
"Time to Full Charge" = 0;
"Transport Type" = Internal;
Type = InternalBattery;
}
)