I want to setup a Playground to fetch the battery status of my macbook.
I have already tried the following:
import Cocoa
import IOKit
import Foundation
var blob = IOPSCopyPowerSourcesInfo()
I am currently receiving an error as below
Use of unresolved identifier 'IOPSCopyPowerSourcesInfo'
It doesn't work in a Playground, but it works in a real app.
I couldn't access the
IOPowerSources.h
header file with Swift andimport IOKit
only, though: I had to make a bridge to Objective-C.Here's my solution:
Add
IOKit.framework
to your project (click+
inLinked Frameworks and Libraries
)Create a new empty
.m
file, whatever its name. Xcode will then ask if it should make a "bridging header". Say YES.Ignore the
.m
file. In the newYOURAPPNAME-Bridging-Header.h
file that Xcode just created, add the line#import <IOKit/ps/IOPowerSources.h>
(and don't addimport IOKit
in your Swift file)You can now access most of the
IOPowerSources
functions.Example:
Note: I couldn't access constants like
kIOPSTimeRemainingUnlimited
andkIOPSTimeRemainingUnknown
so I used their raw values (-2.0 and -1.0) but it would be better to find these constants if they still exist somewhere.Another example, with
IOPSCopyPowerSourcesInfo
:Result: