2013-06-26 132 views
1

我有下面的方法,正確返回電池電量但沒有得到電池狀態。它總是返回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; 
} 

如何從UIDevice返回正確的電池狀態?

+1

http://stackoverflow.com/a/16850740/1710611 – rog

回答

8

嘗試在切換前移動此行。

[device setBatteryMonitoringEnabled:YES]; 

默認禁用的電池監視將阻止您正確讀取電池狀態。

+0

它的工作原理!我一直盯着它太久了。謝謝。 – motionpotion