[UIDevice currentDevice].batteryMonitoringEnabled = YES;double deviceLevel = [UIDevice currentDevice].batteryLevel;
To obtain the remaining power, we usually use the above method. This is also provided in Apple's official documentation.
It returns a floating point value between 0.00 and 1.00. In addition,-1.00 indicates the simulator.
It seems that this method is good and very simple.
However, we can find that we carefully observe the returned values.It is incrementally changed to 0.05. If it is converted to 100%, It is incrementally changed to 5%.
That is to say, this method is flawed. At the very least, it is not accurate.
Then I found a method. It is quite accurate and the error is kept within 1%.
We know that there is an IOKit. framework library in Mac. It can calculate the required power.
If you want to use it, (iOS does not provide it) You can first create a project under Mac, find IOKit. framework, then the IOKit. frameworkIOPowerSources. hAndIOPSKeys. hCopy to your iOS project. In additionIOKitIt is also imported into your project.
(If it is too troublesome, you can directly download the project from my Github and export the required files)
First give my Github download link: https://github.com/colin1994/batteryLevelTest.git
The following describes how to use it.
1. Import IOPowerSources. h, IOPSKeys. h, and IOKit
2. Declare the header file in the implementation
#import "IOPSKeys.h"#import "IOPowerSources.h"
3. Add Method
/** * 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. Call Method
NSLog(@"%.2f", [self getCurrentBatteryLevel]);