Search code examples
iosobjective-cnsnotificationcenteruidevice

UIDeviceBatteryLevelDidChangeNotification background notifications?


We are looking to develop an app which will alert users if their battery level drops below a certain percentage however we are finding that our application does not seen to get this NSNotifications when it is not active.

Does any one have any experience of using the UIDeviceBattery Notifications and know if this is at all possible as from what I can see from the Apple Documentation it seems that it should work.

We are basically doing this

-(void)startMonitoring {

    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
    [[UIDevice currentDevice] batteryLevel];

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

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStatus) name:UIDeviceBatteryStateDidChangeNotification object:nil];

[self redirectNSLogToDocuments];
NSLog(@"Starting Monitoring");
}

- (void)redirectNSLogToDocuments
{
    NSArray *allPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [allPaths objectAtIndex:0];
    NSString *pathForLog = [documentsDirectory stringByAppendingPathComponent:@"yourFile.txt"];

    freopen([pathForLog cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}

- (void)batteryStatus {

    NSLog(@"Battery Status Notification");
}

So once we kick the battery monitoring off our log file populates with the initial message then as a test I close the app and go to the home screen and disconnect my laptop power cable a few times which should trigger a battery status log, however this is not the case.

Thanks in advance Aaron


Solution

  • NSNotifications are not delivered to your app while in background. So, unless your app can ask for some of the Background Modes permissions, there is no way to execute that code in background.

    Take a look at https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH4-SW4 to see if you can use some of those modes.