17

I am using :

UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
float batLeft = [myDevice batteryLevel];
int i = [myDevice batteryState];    
int batinfo = batLeft * 100;

to find the battery status. I am looking out to find, how to find the time remaining until the charge is complete. ex: 1 hour 20 min remaining. How can I find it programmatically?

Shishir.bobby
  • 10,994
  • 21
  • 71
  • 100

1 Answers1

10

I haven't found any method for this in the official documentation, neither in the class-dumped, private header of the UIDevice class.

So we have to come up with something. The best "solution" I have in mind at the moment is similar to the approach taken when estimating download time: calculating an average speed of download/charging, and dividing the remaining amount (of data or charge) by that speed:

[UIDevice currentDevice].batteryMonitoringEnabled = YES;
float prevBatteryLev = [UIDevice currentDevice].batteryLevel;
NSDate *startDate = [NSDate date];

[[NSNotificationCenter defaultCenter]
    addObserver:self
       selector:@selector(batteryCharged)
           name:UIDeviceBatteryLevelDidChangeNotification
         object:nil
];

- (void)batteryCharged
{
    float currBatteryLev = [UIDevice currentDevice].batteryLevel;
    // calculate speed of chargement
    float avgChgSpeed = (prevBatteryLev - currBatteryLev) / [startDate timeIntervalSinceNow];
    // get how much the battery needs to be charged yet
    float remBatteryLev = 1.0 - currBatteryLev;
    // divide the two to obtain the remaining charge time
    NSTimeInterval remSeconds = remBatteryLev / avgChgSpeed;
    // convert/format `remSeconds' as appropriate
}
  • 4
    That assumes that charging is linear -- it isn't. Charging slows down dramatically as the battery gets close to full. –  Dec 16 '12 at 07:27
  • @duskwuff yes, and even the battery level reported by the OS may not be exact, etc. Why do you think I used the term **"average"** throughout? Shit happens... –  Dec 16 '12 at 07:29
  • Thanks H2CO3, i am not able to call batterCharge method.any suggestion – Shishir.bobby Dec 16 '12 at 07:37
  • @iscavengers Why "are you not able" to call that method? Even more important: why would you need to call it? It's called by the notification center. You just do something in the end of the method with the obtained `remSeconds` value. –  Dec 16 '12 at 07:41
  • finally it worked. but on NSLog i am getting this : remSeconds : -inf – Shishir.bobby Dec 16 '12 at 08:15
  • @iscavengers that means `avgChgSpeed` was 0 for some reason. Time to fire up the debugger. –  Dec 16 '12 at 08:23
  • @iscavengers so how are you trying to use it? –  Dec 23 '12 at 17:48