Created
September 14, 2015 04:00
-
-
Save khakionion/720a949b3beb5f6d1e4c to your computer and use it in GitHub Desktop.
Access battery info (current, remaining charge, cycle count etc) in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.swift | |
// battstat | |
// | |
// Created by Michael Herring on 2015/09/14. | |
// Copyright (c) 2015年 Michael Herring. All rights reserved. | |
// | |
import Foundation | |
import IOKit.ps | |
import IOKit.pwr_mgt | |
//get power sources array | |
let powerSourcesInfo : AnyObject! = IOPSCopyPowerSourcesInfo().takeUnretainedValue() | |
let batteryArray : NSArray = IOPSCopyPowerSourcesList(powerSourcesInfo).takeUnretainedValue() | |
//get power management object | |
let nullPort : UInt32 = UInt32(MACH_PORT_NULL) | |
let powerManagement : io_connect_t = IOPMFindPowerManagement(nullPort) | |
//get power management battery info array | |
let batteryInfoPtr : UnsafeMutablePointer<Unmanaged<CFArray>?> = UnsafeMutablePointer.alloc(sizeof(Unmanaged<CFArray>?)) | |
let batteryResult:IOReturn = IOPMCopyBatteryInfo(nullPort, batteryInfoPtr) | |
let batteryInfo:NSArray? = batteryInfoPtr.memory?.takeUnretainedValue() | |
//close service | |
IOServiceClose(powerManagement) | |
//output data | |
var batteryIndex:Int = 0 | |
for nextSource in batteryArray | |
{ | |
print("Battery "+String(batteryIndex)+" Status:") | |
print(nextSource) | |
let pmBatteryPtr:UnsafePointer<Void> = CFArrayGetValueAtIndex(batteryInfo, batteryIndex++) | |
let pmBattery:Dictionary = unsafeBitCast(pmBatteryPtr, CFDictionary.self) as Dictionary | |
print(pmBattery) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment