Member-only story

Getting Device Battery State iOS

Mr.Javed Multani
1 min readOct 5, 2020

--

When We need to access the state of the battery for the particular intention in our app we can get it by using following code:

//Get permission for Battery Monitoring[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
UIDevice *myDevice = [UIDevice currentDevice];[myDevice setBatteryMonitoringEnabled:YES];
double batLeft = (float)[myDevice batteryLevel] * 100;
NSLog(@"%.f",batLeft);int d = myDevice.batteryState;
//Returns an Integer Value
//UIDeviceBatteryStateUnknown 0
//UIDeviceBatteryStateUnplugged 1
//UIDeviceBatteryStateCharging 2
//UIDeviceBatteryStateFull 3//Using notifications for Battery Monitoring-(void)startMonitoringForBatteryChanges
{
// Enable monitoring of battery status
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
// Request to be notified when battery charge or state changes
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBatteryStatus) name:UIDeviceBatteryLevelDidChangeNotification object:nil];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBatteryStatus) name:UIDeviceBatteryStateDidChangeNotification object:nil];
}
-(void) checkBatteryStatus{
NSLog (@"Battery Level is %.f",[[UIDevice currentDevice] batteryLevel]*100);int d=[[UIDevice currentDevice] batteryState];
if (d==0){
NSLog(@"Unknown");}
else if (d==1)
{NSLog(@"Unplugged");
}else if (d==2)
{NSLog(@"Charging");
}else if (d==3)
{NSLog(@"Battery Full");
}
}

--

--

Mr.Javed Multani
Mr.Javed Multani

Written by Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer

No responses yet