我已经尝试过以下方法:
import Cocoa import IOKit import Foundation var blob = IOPSCopyPowerSourcesInfo()
我目前收到如下错误
Use of unresolved identifier ‘IOPSCopyPowerSourcesInfo’
我无法使用Swift访问IOPowerSources.h头文件并仅导入IOKit,但是:我必须建立一个与Objective-C的桥梁.
这是我的解决方案:
>将IOKit.framework添加到项目中(单击Linked Frameworks and Libraries)
>创建一个新的空.m文件,无论其名称如何.然后Xcode将询问它是否应该制作“桥接头”.说是的.
>忽略.m文件.在Xcode刚创建的新YOURAPPNAME-Bridging-Header.h文件中,添加#import< IOKit / ps / IOPowerSources.h>行; (并且不要在Swift文件中添加导入IOKit)
>您现在可以访问大多数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)
注意:我无法访问像kIOPSTimeRemainingUnlimited和kIOPSTimeRemainingUnknown这样的常量,所以我使用了它们的原始值(-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; } )