[Uidevice currentdevice].batterymonitoringenabled = yes;double Devicelevel = [Uidevice currentDevice].batteryLevel;
We usually use the above method to get the current remaining charge. This is also provided by Apple's official documentation.
It returns a floating-point value between 0.00-1.00. In addition,-1.00 represents the simulator.
Looks like this method is good, also very simple.
But careful observation of its return value, we can find. It is with 0.05 homologous. Converted to 100%, that is, 5% to homologous.
In other words, this approach is flawed, at the very least, imprecise.
Then a method was found. Accurate, the error remains within 1%.
We know that there is a iokit.framework library under the Mac. It can calculate the amount of power we need.
If we want to use it, (iOS is not provided) can first build a Mac under the project, find Iokit.framework, that iokit.framework inside the IOPowerSources.h and IOPSKeys.h Copy to your iOS project. In addition, IOKit also need to be imported into your project.
(Of course, if you have trouble, you can go directly to my github to download the project, export the required files)
Get my GitHub download link first: https://github.com/colin1994/batteryLevelTest.git
The following is a detailed description of how to use it.
1. Import the required IOPowerSources.h, IOPSKeys.h and IOKit
2. Declaring header files in place of implementation
#import "IOPSKeys.h" #import "IOPowerSources.h"
3. Add method
/** * Calculating the remaining energy * * @return current Batterylevel */-(double) getcurrentbatterylevel{//retu RNs a blob of Power Source information in an opaque cftyperef. Cftyperef blob = Iopscopypowersourcesinfo (); Returns a cfarray of Power Source handles, each of the 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 cfdicti Onary 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. Calling methods
NSLog (@ "%.2f", [self getcurrentbatterylevel]);