是否有与 macOS 上的 kIOPSCurrentCapacityKey 等效的电池电量变化通知?

W. *_*ook 5 macos cocoa iokit batterylevel swift

我正在构建一个 Swift 应用程序,用于监控 Mac 笔记本电脑电池的电池百分比以及充电状态。在 iOS 上,batteryLevelDidChange设备电池百分比变化时会发送通知,batteryStateDidChange设备插入、拔出插头和充满电时也会发送通知。

Swift 中这两个通知在 macOS 中的等效项是什么,或者更具体地说,对于kIOPSCurrentCapacityKeykIOPSIsChargingKey?我通读了通知文档,但没有看到任何通知。这是我用于获取当前电池电量和充电状态的代码:

import Cocoa
import IOKit.ps

class MainViewController: NSViewController {

enum BatteryError: Error { case error }

func getMacBatteryPercent() {

    do {
        guard let snapshot = IOPSCopyPowerSourcesInfo()?.takeRetainedValue()
            else { throw BatteryError.error }

        guard let sources: NSArray = IOPSCopyPowerSourcesList(snapshot)?.takeRetainedValue()
            else { throw BatteryError.error }

        for powerSource in sources {
            guard let info: NSDictionary = IOPSGetPowerSourceDescription(snapshot, ps as CFTypeRef)?.takeUnretainedValue()
                else { throw BatteryError.error }

            if let name = info[kIOPSNameKey] as? String,
                let state = info[kIOPSIsChargingKey] as? Bool,
                let capacity = info[kIOPSCurrentCapacityKey] as? Int,
                let max = info[kIOPSMaxCapacityKey] as? Int {
                print("\(name): \(capacity) of \(max), \(state)")
            }
        }
    } catch {
        print("Unable to get mac battery percent.")
    }
}

override func viewDidLoad() {
    super.viewDidLoad() 

    getMacBatteryPercent()
}
}
Run Code Online (Sandbox Code Playgroud)

Ker*_*omo 6

(我正在回答这个近三年前的问题,因为这是 Google 搜索“swift iokit notification”中出现的第三个结果。)

您正在寻找的函数是IOPSNotificationCreateRunLoopSourceIOPSCreateLimitedPowerNotification

最简单的用法IOPSNotificationCreateRunLoopSource

import IOKit

let loop = IOPSNotificationCreateRunLoopSource({ _ in
    // Perform usual battery status fetching
}, nil).takeRetainedValue() as CFRunLoopSource
CFRunLoopAddSource(CFRunLoopGetCurrent(), loop, .defaultMode)
Run Code Online (Sandbox Code Playgroud)

请注意,第二个参数context作为回调函数中的唯一参数传递,可用于将实例作为指向闭包的指针传递,因为 C 函数不捕获上下文。(具体实施请参见下面的链接。)

下面是我的代码,它使用观察者模式将 C 风格的 API 转换为更 Swift 友好的 API:(不知道删除运行循环会带来多少性能优势)

import Cocoa
import IOKit

// Swift doesn't support nested protocol(?!)
protocol BatteryInfoObserverProtocol: AnyObject {
    func batteryInfo(didChange info: BatteryInfo)
}

class BatteryInfo {
    typealias ObserverProtocol = BatteryInfoObserverProtocol
    struct Observation {
        weak var observer: ObserverProtocol?
    }
    
    static let shared = BatteryInfo()
    private init() {}
    
    private var notificationSource: CFRunLoopSource?
    var observers = [ObjectIdentifier: Observation]()
    
    private func startNotificationSource() {
        if notificationSource != nil {
            stopNotificationSource()
        }
        notificationSource = IOPSNotificationCreateRunLoopSource({ _ in
            BatteryInfo.shared.observers.forEach { (_, value) in
                value.observer?.batteryInfo(didChange: BatteryInfo.shared)
            }
        }, nil).takeRetainedValue() as CFRunLoopSource
        CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationSource, .defaultMode)
    }
    private func stopNotificationSource() {
        guard let loop = notificationSource else { return }
        CFRunLoopRemoveSource(CFRunLoopGetCurrent(), loop, .defaultMode)
    }
    
    func addObserver(_ observer: ObserverProtocol) {
        if observers.count == 0 {
            startNotificationSource()
        }
        observers[ObjectIdentifier(observer)] = Observation(observer: observer)
    }
    func removeObserver(_ observer: ObserverProtocol) {
        observers.removeValue(forKey: ObjectIdentifier(observer))
        if observers.count == 0 {
            stopNotificationSource()
        }
    }
    
    // Functions for retrieving different properties in the battery description...
}
Run Code Online (Sandbox Code Playgroud)

用法:

class MyBatteryObserver: BatteryInfo.ObserverProtocol {
    init() {
        BatteryInfo.shared.addObserver(self)
    }
    deinit {
        BatteryInfo.shared.removeObserver(self)
    }
    
    func batteryInfo(didChange info: BatteryInfo) {
        print("Changed")
    }
}
Run Code Online (Sandbox Code Playgroud)

感谢这篇文章和 Koen. 的回答


小智 2

我会使用此链接获取百分比(看起来更干净) 使用 Swift 获取我的 MacBook 的电池状态

要查找状态的变化,请使用 atimer每 5 秒重新声明一次电池状态,然后将其设置为新变量,var OldBattery:Int再次重新声明并将其设置为NewBattery,然后编写以下代码:

if (OldBattery =! NewBattery) {
      print("battery changed!")
      // write the function you want to happen here
}
Run Code Online (Sandbox Code Playgroud)