i think this article will help you very much
The first thing you need to do is modify your app’s plist. Add the following settings.
Application does not run in background: NO
Required background modes: VOIP
And set up the code for when the application launches
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSLog(@"Starting app");
self.powerHandler = [[PowerHandler alloc] init];
self.lastBatteryState = UIDeviceBatteryStateUnknown;
UIApplication* app = [UIApplication sharedApplication];
self.expirationHandler = ^{
[app endBackgroundTask:self.bgTask];
self.bgTask = UIBackgroundTaskInvalid;
self.bgTask = [app beginBackgroundTaskWithExpirationHandler:expirationHandler];
NSLog(@"Expired");
self.jobExpired = YES;
while(self.jobExpired) {
// spin while we wait for the task to actually end.
[NSThread sleepForTimeInterval:1];
}
// Restart the background task so we can run forever.
[self startBackgroundTask];
};
self.bgTask = [app beginBackgroundTaskWithExpirationHandler:expirationHandler];
// Assume that we're in background at first since we get no notification from device that we're in background when
// app launches immediately into background (i.e. when powering on the device or when the app is killed and restarted)
[self monitorBatteryStateInBackground];
return YES;
}
Next, we set up the background job
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(@"Entered background");
[self monitorBatteryStateInBackground];
}
- (void)monitorBatteryStateInBackground
{
NSLog(@"Monitoring battery state");
self.background = YES;
self.lastBatteryState = UIDeviceBatteryStateUnknown;
[self startBackgroundTask];
}
- (void)startBackgroundTask
{
NSLog(@"Restarting task");
// Start the long-running task.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// When the job expires it still keeps running since we never exited it. Thus have the expiration handler
// set a flag that the job expired and use that to exit the while loop and end the task.
while(self.background && !self.jobExpired)
{
[self updateBatteryState:[self.powerHandler checkBatteryState]];
[NSThread sleepForTimeInterval:1];
}
self.jobExpired = NO;
});
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
NSLog(@"App is active");
self.background = NO;
}