質問

I'm using this function to get current battery level of device:

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
UIDevice *myDevice = [UIDevice currentDevice];

[myDevice setBatteryMonitoringEnabled:YES];
double batLeft = (float)[myDevice batteryLevel]; 
NSLog(@"%f",batLeft);

but the result has a 5% granularity. Example: when the phone battery is at 88%, it only logs a value of 0.85. batteryLevel only returns values in increments of 0.05. For example: 0.85, 0.9, 0.95 and never returns values like 0.82 or 0.83.

Is there any solution to get a percentage with a higher precision?

役に立ちましたか?

解決

check out this site : Reading the battery level programmatically

but, carefully use. all of the APIs used here are undocumented on the iPhone, and will probably lead to a rejection if you submit this application to the App Store. Although battery charge status is not exactly, I'd recommend using the UIDevice battery monitoring methods.

他のヒント

There are at least four different ways to read the battery level, and all four ways may return different values.

Here is a chart of these values through time.

The values were recorded with this iOS project: https://github.com/nst/BatteryChart

Please check out the code for reference.

iPhone 5 Battery

UIDevice *myDevice = [UIDevice currentDevice];    
[myDevice setBatteryMonitoringEnabled:YES];

double batLeft = (float)[myDevice batteryLevel] * 100;
NSLog(@"%.f", batLeft);    

NSString * levelLabel = [NSString stringWithFormat:@"%.f%%", batLeft];    
lblLevel.text = levelLabel;

Swift version to get the battery level:

UIDevice.current.isBatteryMonitoringEnabled = true
let batteryLevel = UIDevice.current.batteryLevel 

batteryLevel return 0,39; 0,40 values for me.

The answers above are very good, but they are all in Obj-C, I have used these with other examples to do the same task on MonoTouch, so I am putting my code here in case anybody needs it:

try
{
    UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;
    _Battery.Level = (int)(UIDevice.CurrentDevice.BatteryLevel * IOSBatteryLevelScalingFactor);
    _Battery.State = UIDevice.CurrentDevice.BatteryState;
}
catch (Exception e)
{
    ExceptionHandler.HandleException(e, "BatteryState.Update");
    throw new BatteryUpdateException();
}
finally
{
    UIDevice.CurrentDevice.BatteryMonitoringEnabled = false;
}

I also have a full post on my blog to give all the details in here

You can find a perfect answer here

Xcode: 11.4 Swift: 5.2

Click Here

If you are using swift 5.1 or greater this code will definitely work for you.

Step 1:- To get started, first enable the isBatteryMonitoringEnabled property of the current device, like this:-

UIDevice.current.isBatteryMonitoringEnabled = true

Step 2:- You can now read the current battery level

let level = UIDevice.current.batteryLevel
print(level)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top