Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get correct battery level and battery status-ios?

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);
like image 225
Murali Krishna Avatar asked May 21 '15 12:05

Murali Krishna


People also ask

How do I make my iPhone battery percentage accurate?

Just swipe down from the top right-hand corner of your display. With iOS 16, you can turn on the battery percentage so it appears in your status bar. Go to Settings > Battery, and turn on Battery Percentage.

Why is my iPhone telling me the wrong battery percentage?

Reboot your iPhone right before connecting it to a charger. This will cause the proper battery percentage level to be displayed. Connect your device to the charger and allow it to charge fully. Leave it plugged in for at least 3 hours.

Why is my battery percentage incorrect?

The reason for this is simple. Batteries naturally degrade over time, and their capacity slowly decreases. But your phone isn't always great at measuring that—if your battery has degraded to 95% of its original capacity, your phone might still report that as 95% full, instead of 100% full (the “new normal”).


1 Answers

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.

like image 180
Massimo Polimeni Avatar answered Oct 13 '22 18:10

Massimo Polimeni