Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Battery State Always Returning Null

I have the method below that returns the battery charge level correctly but does not get the battery state. It always returns UNKNOWN.

-(NSString *)batteryStatus
{
UIDevice *device = [UIDevice currentDevice];
NSString *batteryStateString = nil;
switch(device.batteryState)
{
    case UIDeviceBatteryStateUnplugged: batteryStateString = @"Unplugged"; break;
    case UIDeviceBatteryStateCharging: batteryStateString = @"Charging"; break;
    case UIDeviceBatteryStateFull: batteryStateString = @"Full"; break;
    default: batteryStateString = @"Unknown"; break;
}

[device setBatteryMonitoringEnabled:YES];
NSString *statusString = [NSString stringWithFormat:@"Level - %d%% - State - %@",
                          (int)round(device.batteryLevel * 100), batteryStateString];
[device setBatteryMonitoringEnabled:NO];
return statusString;
}

How can I return the correct batterystate from UIDevice?

like image 834
motionpotion Avatar asked Jun 29 '26 22:06

motionpotion


1 Answers

Try moving this line before the switch.

[device setBatteryMonitoringEnabled:YES];

A default disabled battery monitoring would prevent you from reading the battery state correctly.

like image 92
Alexander Avatar answered Jul 02 '26 12:07

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!