1

我试图获得正确的电池电量。但该值不像 iphone 状态栏中的值。

通过代码使用 UIDevice:

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

[[UIDevice currentDevice] batteryLevel];

请有人帮助我!我需要获得正确的电池电量,就像在状态栏 imdimatery 中一样。

4

2 回答 2

10

好吧,Apple 文档是这样说的:

电池电量范围从 0.0(完全放电)到 1.0(100% 充电)。在访问此属性之前,请确保已启用电池监控。

所以你的代码应该是这样的:

[[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;

希望这可以帮助!

于 2012-08-03T20:44:36.163 回答
2

获取电池电量的Swift版本:

UIDevice.current.isBatteryMonitoringEnabled = true
let batteryLevel = UIDevice.current.batteryLevel * 100
于 2019-02-21T14:29:06.923 回答