I\'m using this function to get current battery level of device:
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
UIDevice *myDevice = [UIDevice c
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)
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;
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
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.
You can find a perfect answer here
Xcode: 11.4 Swift: 5.2
Click Here
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.