快速获取mac上的电池百分比

时间:2016-01-02 22:07:58

标签: swift macos

您好我想知道如何迅速获得当前的电池容量。

我有这段代码

    let batteryStatus = getBatteryStatus()
    print(batteryStatus)

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

    let PowerDetail = list.takeRetainedValue()

    print(PowerDetail)

这是我的输出

(
    {
    "Battery Provides Time Remaining" = 1;
    BatteryHealth = Good;
    Current = 3907;
    "Current Capacity" = 57;
    DesignCycleCount = 1000;
    "Is Charging" = 1;
    "Is Finishing Charge" = 0;
    "Is Present" = 1;
    "Max Capacity" = 100;
    Name = "InternalBattery-0";
    "Power Source State" = "AC Power";
    "Time to Empty" = 0;
    "Time to Full Charge" = 120;
    "Transport Type" = Internal;
    Type = InternalBattery;
}

现在我如何获得"当前容量"

谢谢

1 个答案:

答案 0 :(得分:6)

import Foundation
import IOKit.ps

// Take a snapshot of all the power source info
let snapshot = IOPSCopyPowerSourcesInfo().takeRetainedValue()

// Pull out a list of power sources
let sources = IOPSCopyPowerSourcesList(snapshot).takeRetainedValue() as Array

// For each power source...
for ps in sources {
    // Fetch the information for a given power source out of our snapshot
    let info = IOPSGetPowerSourceDescription(snapshot, ps).takeUnretainedValue() as! [String: AnyObject]

    // Pull out the name and capacity
    if let name = info[kIOPSNameKey] as? String,
        let capacity = info[kIOPSCurrentCapacityKey] as? Int,
        let max = info[kIOPSMaxCapacityKey] as? Int {
        print("\(name): \(capacity) of \(max)")
    }
}

请记住,“当前容量”可能并不意味着您认为这意味着什么。容量单位由供应商定义。 Apple电源的发布容量为0-100%,但其他供应商可以提供其他单位的信息(例如mAh)。您需要除以最大容量才能获得有意义的结果。

/*!
 * @define      kIOPSCurrentCapacityKey
 * @abstract    CFDictionary key for the current power source's capacity.
 * 
 * @discussion
 *              <ul>
 *              <li> Apple-defined power sources will publish this key in units of percent.
 *              <li> The power source's software may specify the units for this key. 
 *                   The units must be consistent for all capacities reported by this power source.
 *                   The power source will usually define this number in units of percent, or mAh.
 *              <li> Clients may derive a percentage of power source battery remaining by dividing "Current Capacity" by "Max Capacity"
 *              <li> For power source creators: Providing this key is REQUIRED.
 *              <li> Type CFNumber kCFNumberIntType (signed integer)
 *              </ul>
 */

请注意,此代码有些危险。它假设一路上没有错误。如果有错误,你会崩溃。很难想象这里的错误并不表示主要的电力系统故障,在这种情况下,崩溃这个应用程序可能是我们最不关心的问题,但即便如此,更谨慎可能是合理的。如果是这样,你会写这样的东西,这有点复杂,但更安全:

import Foundation
import IOKit.ps

enum BatteryError: Error { case error }

do {
    // Take a snapshot of all the power source info
    guard let snapshot = IOPSCopyPowerSourcesInfo()?.takeRetainedValue()
        else { throw BatteryError.error }

    // Pull out a list of power sources
    guard let sources: NSArray = IOPSCopyPowerSourcesList(snapshot)?.takeRetainedValue()
        else { throw BatteryError.error }

    // For each power source...
    for ps in sources {
        // Fetch the information for a given power source out of our snapshot
        guard let info: NSDictionary = IOPSGetPowerSourceDescription(snapshot, ps as CFTypeRef)?.takeUnretainedValue()
            else { throw BatteryError.error }

        // Pull out the name and current capacity
        if let name = info[kIOPSNameKey] as? String,
            let capacity = info[kIOPSCurrentCapacityKey] as? Int,
            let max = info[kIOPSMaxCapacityKey] as? Int {
            print("\(name): \(capacity) of \(max)")
        }
    }
} catch {
    fatalError()
}