1

I am trying to display battery percentage with UILabel , but the result is nonsense ! here is my code :

UIDevice *myDevice = [UIDevice currentDevice];
    [myDevice setBatteryMonitoringEnabled:YES];
    int i=[myDevice batteryState];
    _battery.text = [NSString stringWithFormat:@"%i",i];

the labels shows number 2 !!!!

meth
  • 1,887
  • 2
  • 18
  • 33
Mc.Lover
  • 4,813
  • 9
  • 46
  • 80

3 Answers3

2

Use below code to get battery level

UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
float batteryLevel = [myDevice batteryLevel];
_battery.text = [NSString stringWithFormat:@"%f",batteryLevel*100];

[myDevice batteryLevel]; will give you the battery between 0.0 (empty) and 1.0 (100% charged)

Hope it helps..

Ankur
  • 5,086
  • 19
  • 37
  • 62
  • worth noting that 'setBatteryMonitoringEnabled' method isn't thread safe, as mentioned in https://github.com/jszumski/uidevice-threading-crash, http://openradar.appspot.com/13941890, https://twitter.com/cheesemaker/status/517373206748205056. – yonivav Jan 03 '17 at 10:03
1

iPhone OS provides two type of battery monitoring events, one for when the state changes (e.g., charging, unplugged, full charged) and one that updates when the battery’s charge level changes. As was the case with proximity monitoring, you register callbacks to receive notifications:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryStateDidChangeNotification" object:device];

ALso refer this link.

iPatel
  • 46,010
  • 16
  • 115
  • 137
0
[myDevice batteryState];//return is a variable of UIDeviceBatteryState

the labels shows number 2 means"UIDeviceBatteryStateCharging, // plugged in, less than 100%",if you want to display battery percentage. The code in the first answer will help you.

haibarahu
  • 49
  • 8