iOS: how to get correctly battery level

前端 未结 2 1473
[愿得一人]
[愿得一人] 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!

    0 讨论(0)
  • 2020-12-18 16:41

    Swift version to get the battery level:

    UIDevice.current.isBatteryMonitoringEnabled = true
    let batteryLevel = UIDevice.current.batteryLevel * 100
    
    0 讨论(0)
提交回复
热议问题