Mur*_*hna 5 objective-c uidevice ios
始终[myDevice batteryLevel]返回-1并[myDevice batterystate]返回0(进入默认情况).
我怎样才能得到正确的值?.任何人都可以帮我解决这个问题吗?.Below是我的代码.(始终将batteryLeft打印为"-100%",电池状态为"未知").
码:
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);
Run Code Online (Sandbox Code Playgroud)
你的代码看起来没问题,就像我在我的应用程序中使用的一样:
-(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);
}
Run Code Online (Sandbox Code Playgroud)
您的问题可能是您在模拟器中尝试此操作,它无法正常工作.
试试一个真实的设备.
| 归档时间: |
|
| 查看次数: |
6864 次 |
| 最近记录: |