[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.h和IOPSKeys.h拷貝到你的iOS項目中。另外, 還需要把IOKit也匯入到你的工程中去。
(當然, 如果嫌麻煩, 可以直接到我的Github中去下載工程, 匯出需要的檔案)
先給出我的Github下載連結:https://github.com/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]);