質問

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?

役に立ちましたか?

解決

Try moving this line before the switch.

[device setBatteryMonitoringEnabled:YES];

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top