/
BDPowerInfo.m
56 lines (42 loc) · 1.43 KB
/
BDPowerInfo.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#import <IOKit/ps/IOPowerSources.h>
#import <IOKit/ps/IOPSKeys.h>
#import "BDPowerInfo.h"
@implementation BDPowerInfo
- (id)IOKitPowerSourceKey:(id)key {
id result = nil;
CFTypeRef info = IOPSCopyPowerSourcesInfo();
CFArrayRef list = IOPSCopyPowerSourcesList(info);
for(int i = 0; i < CFArrayGetCount(list); i++) {
CFDictionaryRef description = IOPSGetPowerSourceDescription(info, CFArrayGetValueAtIndex(list, i));
if(description != NULL) {
result = (__bridge id)CFDictionaryGetValue(description, (__bridge void *)key);
if(result)
break;
}
}
CFRelease(list);
CFRelease(info);
return result;
}
#pragma mark -
- (NSInteger)remainingCharge {
NSInteger currentCharge = [[self IOKitPowerSourceKey:@kIOPSCurrentCapacityKey] integerValue];
NSInteger maxCharge = [[self IOKitPowerSourceKey:@kIOPSMaxCapacityKey] integerValue];
return (currentCharge * 100) / maxCharge;
}
- (BOOL)isRunningOnBattery {
return [[self IOKitPowerSourceKey:@kIOPSPowerSourceStateKey] isEqualToString:@kIOPSBatteryPowerValue];
}
- (BOOL)isChargingBattery {
return [[self IOKitPowerSourceKey:@kIOPSIsChargingKey] boolValue];
}
#pragma mark -
+ (id)sharedPowerInfo {
static dispatch_once_t onceToken;
static BDPowerInfo *powerInfo = nil;
dispatch_once(&onceToken, ^{
powerInfo = [[self alloc] init];
});
return powerInfo;
}
@end