Obtain the Battery Level of the IOS device.
This topic describes how to use an API to obtain the power of an IOS device.
The power consumption of mobile devices has always been a major problem. In APP development, it is inevitable to collect information about the power consumption during APP operation, which is also one of the criteria for measuring APP performance.
First, enable the battery statistics in the iphone settings.
1. Obtain from Instruments
The Energy Diagnostics tool provided by Instruments can obtain the power consumption information of the iphone during a specific period of time. Procedure:
Choose Start Logging in the Developer option> disconnect iphone from PC> A series of user operations> Stop Logging> connect iphone to PC to import power consumption data to Instruments.
However, the information obtained in this way is not very intuitive.
2. Get it through UIDevice
UIDevice provides detailed information about the current ios device, such as name, systemVersion, localizedModel, and batteryLevel.
UIDevice.currentDevice.batteryMonitoringEnabled = truelet batteryLevel = UIDevice.currentDevice().batteryLevelUIDevice.currentDevice.batteryMonitoringEnabled = false
The power of the IOS system can be obtained through the UIDevice, but before IOS 8.0, The batteryLevel in the UIDevice can only be accurate to 5%. You need to obtain the power information of 1% precision in other ways. After IOS 8.0, 1% accuracy is supported.
3. Get it through IOKit framework
IOKit framework is used in IOS to communicate with hardware or kernel services. It is often used to obtain hardware details.
First, import the IOPowerSources. h, IOPSKeys. h, and IOKit files to the project. Then, you can obtain the power information with 1% accuracy using the following code:
-(double) getBatteryLevel{ // 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
Of course, the premise is still to set batteryMonitoringEnabled to true.
Finally, you can view and analyze the power consumption of the APP.