失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > iOS开发- 获取精确剩余电量

iOS开发- 获取精确剩余电量

时间:2019-08-07 04:00:42

相关推荐

iOS开发- 获取精确剩余电量

[UIDevice currentDevice].batteryMonitoringEnabled = YES;double deviceLevel = [UIDevice currentDevice].batteryLevel;

获取当前剩余电量, 我们通常采用上述方法。这也是苹果官方文档提供的。

它返回的是0.00-1.00之间的浮点值。 另外, -1.00表示模拟器。

貌似这个方法不错, 也很简单。

但是仔细观察它的返回值, 我们可以发现。它是以0.05递变的。 折算成100% 也就是以5%来递变的。

也就是说, 这个办法是存在缺陷的, 最起码, 它不精确。

后来找到了一个方法。相当精确, 误差保持在1%以内。

我们知道, Mac下有个IOKit.framework库。 它可以计算出我们需要的电量。

如果我们要使用它的话, (iOS是不提供的) 可以先建立一个Mac下的工程,找到IOKit.framework,那IOKit.framework里面的IOPowerSources.hIOPSKeys.h拷贝到你的iOS项目中。另外, 还需要把IOKit也导入到你的工程中去。

(当然, 如果嫌麻烦, 可以直接到我的Github中去下载工程, 导出需要的文件)

先给出我的Github下载链接:/colin1994/batteryLevelTest.git

下面具体介绍下使用方法。

1。导入需要的IOPowerSources.h, IOPSKeys.h 和 IOKit

2。在实现的地方声明头文件

#import "IOPSKeys.h"#import "IOPowerSources.h"

3。添加方法

/*** Calculating the remaining energy** @return Current batterylevel*/-(double)getCurrentBatteryLevel{ //Returns a blob of Power Source information in an opaque CFTypeRef. CFTypeRef blob = IOPSCopyPowerSourcesInfo(); //Returns a CFArray of Power Source handles, each of type CFTypeRef. CFArrayRef sources = IOPSCopyPowerSourcesList(blob); CFDictionaryRef pSource = NULL; const void *psValue; //Returns the number of values currently in an array. int numOfSources = CFArrayGetCount(sources); //Error in CFArrayGetCount if (numOfSources == 0) { NSLog(@"Error in CFArrayGetCount"); return -1.0f; } //Calculating the remaining energy for (int i = 0 ; i < numOfSources ; i++) { //Returns a CFDictionary with readable information about the specific power source. pSource = IOPSGetPowerSourceDescription(blob, CFArrayGetValueAtIndex(sources, i)); if (!pSource) { NSLog(@"Error in IOPSGetPowerSourceDescription"); return -1.0f; } psValue = (CFStringRef)CFDictionaryGetValue(pSource, CFSTR(kIOPSNameKey)); int curCapacity = 0; int maxCapacity = 0; double percent; psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSCurrentCapacityKey)); CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity); psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSMaxCapacityKey)); CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity); percent = ((double)curCapacity/(double)maxCapacity * 100.0f); return percent; } return -1.0f;}

4。调用方法

NSLog(@"%.2f", [self getCurrentBatteryLevel]);

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!/jiangjunshow

如果觉得《iOS开发- 获取精确剩余电量》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。