0

I want to display the battery status of my device in iOS.

I am writing the following code to display the battery status.

UIDevice *myDevice = [UIDevice currentDevice];

[myDevice setBatteryMonitoringEnabled:YES];
double batLeft = (float)[myDevice batteryLevel] * 100;
NSLog(@"%.f",batLeft);
NSString * levelLabel = [NSString stringWithFormat:@"%.f%%", batLeft];
lblLabel.text =levelLabel;

It displays battery status fine when app runs. But, when the app is in background it didn't take the updated value. I want to display the battery status what the device has at every time. I also want to fire a notification when battery was dying between 2 to 3%.

Ben
  • 51,770
  • 36
  • 127
  • 149
user1813959
  • 17
  • 1
  • 5

2 Answers2

2

In order to achieve what you want to do your application you will need to acquire permission to run the background. The only provision made for apps to run in the background is apps which need to play background audio, like music players or VOIP clients. If this is just a test application and you don't intend to publish it via the app store, you can use AVAudioSession to acquire background permissions and poll the battery status. If you intend to publish the app, the scenario in which your application acquires background permissions must benefit the user. i.e. it must play music or handle phone calls.

Abizern
  • 146,289
  • 39
  • 203
  • 257
Chris Hinkle
  • 4,304
  • 1
  • 16
  • 11
1

Here is an example to check the battery every second. You need to check when the battery status in changed, but I presume your current code is read only once in the viewDidLoad.

- (void)viewDidLoad {
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(checkBattery) userInfo:nil repeats:YES];
}



- (void)checkBattery {

    [myDevice setBatteryMonitoringEnabled:YES];
    double batLeft = (float)[myDevice batteryLevel] * 100;
    NSLog(@"%.f",batLeft);
    NSString * levelLabel = [NSString stringWithFormat:@"%.f%%", batLeft];
    lblLabel.text =levelLabel;

}
BalestraPatrick
  • 9,944
  • 4
  • 30
  • 43