質問

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIDevice *device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryStateDidChangeNotification" object:device];
}

- (void)batteryChanged:(NSNotification *)notification
{
    UIDevice *device = [UIDevice currentDevice];
    NSLog(@"State: %i Charge: %f", device.batteryState, device.batteryLevel);
    batteryLabel.text = [NSString stringWithFormat:@"State: %i Charge: %f", device.batteryState, device.batteryLevel];
}

The UILabel is never updated. The event for the power source is never fired.

Am I doing something wrong?

I plan on only supporting iOS 5.x and 6

役に立ちましたか?

解決 2

IBOutlet UILabel *currentBatteryStatusLabel;

I changed the above code into the following and everything started working.

__weak IBOutlet UILabel *currentBatteryStatusLabel;

I am not sure why it makes such a big difference

他のヒント

If you get the notification center working, but the UILabel isn't updating, isn't it simply because the app is in background when the notification is received?

I would try the following:

  1. See if the uilabel is correctly connected to the storyboard
  2. Update the uilabel once the app is awakened from sleep
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top