- (IBAction)buttonPressed:(id)sender
{
UIDevice *device = [UIDevice currentDevice];
device.batteryMonitoringEnabled = YES;
if ([[UIDevice currentDevice] isMultitaskingSupported]) {
[self beingBackgroundUpdateTask];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryStateDidChangeNotification" object:device];
[self currentBatteryState];
}
- (void) beingBackgroundUpdateTask
{
self->backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundUpdateTask];
}];
}
- (void) endBackgroundUpdateTask
{
[[UIApplication sharedApplication] endBackgroundTask: self->backgroundUpdateTask];
self->backgroundUpdateTask = UIBackgroundTaskInvalid;
}
For some reason, the notification’s are not being observed. Am i doing something wrong? I want to observe for unto 10 minutes when unplugged
You shouldn’t be calling
endBackgroundUpdateTaskin yourbuttonPressed:method, since that cancels your background task. Try removing this code:Also, you should pass the
UIDeviceBatteryLevelDidChangeNotificationconstant to the “name” parameter, not the string. It should look like this (note the lack of double quotes):(It’s also possible that UIDevice simply doesn’t send those notifications in the background.)