5

Always [myDevice batteryLevel] returning -1 and [myDevice batterystate]returning 0(entering into Default case).

How can i get the correct values?.Can anyone please help me to solve this?.Below is my code.(Always Printing batteryLeft as "-100%" and Battery Status as "Unknown").

Code:

UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
float batLeft = [myDevice batteryLevel]*100;
int status=[myDevice batteryState];
NSLog(@"level:%0.0f",batLeft);
NSString *status_str;
switch (status)
{
    case UIDeviceBatteryStateUnplugged:
    {
        NSLog(@"UnpluggedKey");
        status_str=@"UnPlugged";
        break;
    }
    case UIDeviceBatteryStateCharging:
    {
        NSLog(@"ChargingKey");
        status_str=@"Charging";
        break;
    }
    case UIDeviceBatteryStateFull:
    {
        NSLog(@"FullKey");
        status_str=@"BatteryFul";
        break;
    }

default:
{
    NSLog(@"UnknownKey");
    status_str=@"Unknown";
    break;
}
}
NSLog(@"Battery status:%@",status_str);
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Murali Krishna
  • 167
  • 4
  • 17
  • 4
    Are you testing on device or simulator? testing on simulator will give you the output that your are getting now. :-) – Vivek Molkar May 21 '15 at 12:19

2 Answers2

9

Your code looks to be ok, it's the same that I used in one of my app:

-(void) battery
{
    UIDevice *myDevice = [UIDevice currentDevice];
    [myDevice setBatteryMonitoringEnabled:YES];

    int state = [myDevice batteryState];
    NSLog(@"battery status: %d",state); // 0 unknown, 1 unplegged, 2 charging, 3 full

    double batLeft = (float)[myDevice batteryLevel] * 100;
    NSLog(@"battery left: %ld", batLeft);
}

Your problem can be that you try this in the simulator, where it can't be work.

Try on one real device.

Massimo Polimeni
  • 4,826
  • 4
  • 27
  • 54
  • How is this code any different than what is already in the question? Please explain how this solves the issue. – rmaddy May 21 '15 at 14:21
3

I hope you are not checking it on your simulator :)

You will not get exact battery level of your device , its always in multiple of 0.05. That means if your device battery level is 78% then it will show 75%.

if you want exact battery level indication then you can follow this link :http://blog.coriolis.ch/2009/02/14/reading-the-battery-level-programmatically/

Ankush
  • 132
  • 1
  • 11