Remove the battery status of my MacBook using Swift

I want to configure the playing field to load the battery status of my macbook.

I have already tried the following:

import Cocoa
import IOKit
import Foundation

var blob = IOPSCopyPowerSourcesInfo()

I am currently getting the error message below

Using an Unresolved Identifier "IOPSCopyPowerSourcesInfo"

+4
source share
1 answer

It does not work on the playground, but it works in a real application.

I could not access the header file IOPowerSources.honly with Swift and import IOKit, however: I had to make a bridge to Objective-C.

Here is my solution:

  • Add IOKit.frameworkto your project (click +in Linked Frameworks and Libraries)

  • .m , . Xcode , " ". .

  • .m. YOURAPPNAME-Bridging-Header.h, Xcode, #import <IOKit/ps/IOPowerSources.h> ( import IOKit Swift)

  • 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())

:

(
        {
         " " = 1;
        BatteryHealth = ,
        Current = 0;
         " " = 98;
        DesignCycleCount = 1000;
         " " = 1X234567XX8XX;
         "" = 1;
         "" = 0;
         "" = 1;
         " " = 100;
        Name = "InternalBattery-0",
         " " = " ";
         " " = 0;
         " " = 0;
         " " = ;
         = ;
    }
)

+10

Source: https://habr.com/ru/post/1599701/


All Articles