iOS: how to get correctly battery level

前端 未结 2 1607
[愿得一人]
[愿得一人] 2020-12-18 15:51

I have tried to get correctly battery level. But that value is not like value in status bar of iphone.

by code use UIDevice:

[[UIDevice currentDevice         


        
2条回答
  •  无人及你
    2020-12-18 16:36

    Well the Apple docs say this:

    Battery level ranges from 0.0 (fully discharged) to 1.0 (100% charged). Before accessing this property, ensure that battery monitoring is enabled.

    So your code should be like this:

    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
    float batteryLevel = [[UIDevice currentDevice] batteryLevel];
    
    //This will give you the battery between 0.0 (empty) and 1.0 (100% charged)
    //If you want it as a percentage, you can do this:
    
    batteryLevel *= 100;
    

    Hope this helps!

提交回复
热议问题