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;
" " = ;
= ;
}
)