views:

359

answers:

1

Hello there, I am having a small problem. I am a beginner to iPhone programming so please forgive me if the answer is obvious.

I have found the current charge and want it to continually update while my app is running. I tried this:

- (void) viewWillAppear:(BOOL)animated
{

 NSLog(@"viewWillAppear");
 double level = [self batteryLevel];
 currentCharge.text = [NSString stringWithFormat:@"%.2f %%", level];
 timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:selfselector:@selector(updateBatteryLevel:) userInfo:nil repeats:NO];
 [super viewWillAppear:animated];
}

I am correctly getting the reading initially, but it is not updating. Any help would be much appreciated!

Many thanks,

Stuart

+3  A: 

Why would you expect the above code to continuous update? You are setting the value once when the view appears. If you want it continuously update you need to register for the battery status updates and redraw the text when it changes.

Without seeing the code for your batterLevel and updateBatteryLevel: routines there is no way to actually know what you are doing or why they are going wrong. Having said that, I would not use a timer event for this, it is pretty inefficient. You want to use KVO instead:

- (void) viewWillAppear:(BOOL)animated {
  UIDevice *device = [UIDevice currentDevice];
  device.batteryMonitoringEnabled = YES;
  currentCharge.text = [NSString stringWithFormat:@"%.2f", device.batteryLevel];
  [device addObserver:self forKeyPath:@"batteryLevel" options:0x0 context:nil];
  [super viewWillAppear:animated];
}

- (void) viewDidDisappear:(BOOL)animated {
  UIDevice *device = [UIDevice currentDevice];
  device.batteryMonitoringEnabled = NO;
  [device removeObserver:self forKeyPath:@"batteryLevel"];
  [super viewDidDisappear:animated];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  UIDevice *device = [UIDevice currentDevice];
  if ([object isEqual:device] && [keyPath isEqual:@"batteryLevel"]) {
    currentCharge.text = [NSString stringWithFormat:@"%.2f", device.batteryLevel];
  }
}
Louis Gerbarg
Now working so thank you very much Louis. Like I said I am just learning, and can now do this correctly in the future. Thanks again!
Stumf