2

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?

4

1 回答 1

9

Try moving this line before the switch.

[device setBatteryMonitoringEnabled:YES];

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

于 2013-06-26T19:45:46.007 回答