How to accurately obtain the iPhone battery level?

人盡茶涼 提交于 2019-12-10 12:13:48

问题


I want to get the battery level,and Accurate to 1%. I googled and find this,

    CFTypeRef blob = IOPSCopyPowerSourcesInfo();
CFArrayRef sources = IOPSCopyPowerSourcesList(blob);

CFDictionaryRef pSource = NULL;
const void *psValue;

int numOfSources = CFArrayGetCount(sources);
if (numOfSources == 0) {
    NSLog(@"Error in CFArrayGetCount");
    return -1.0f;
}

for (int i = 0 ; i < numOfSources ; i++)
{
    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;

but it's not accurate. So I am asking for help here.


回答1:


From UIDevice Class Reference:

You can use the UIDevice instance to obtain information and notifications about changes to the battery’s charge state (described by the batteryState property) and charge level (described by the batteryLevel property).

[UIDevice currentDevice].batteryMonitoringEnabled = YES;
float batteryLevel = [UIDevice currentDevice].batteryLevel;

NSLog(@"battery level: %f", batteryLevel * 100); 


来源:https://stackoverflow.com/questions/16850480/how-to-accurately-obtain-the-iphone-battery-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!