NOTE: Code is Broken for iOS 13+, many part now deprecated by Apple. BGTaskSheduler new class replacing UIBackground.
I solved my problem, by use the following code in my AppDelegate.m file to keep the server running in the background:
...
bool *isBackground = NO;
- (void)extendBackgroundRunningTime
{
if (isBackground != UIBackgroundTaskInvalid)
return;
NSLog(@"Attempting to extend background running time");
__block Boolean self_terminate = NO; //Do not suspend the application in the background
isBackground = [[UIApplication sharedApplication]
beginBackgroundTaskWithName:@"BackgroundTask" expirationHandler:^
{
if (self_terminate)
{
NSLog(@"Background task expired by iOS");
[[UIApplication sharedApplication] endBackgroundTask:isBackground];
isBackground = UIBackgroundTaskInvalid;
}
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^
{
NSLog(@"Background task started");
while (true)
{
if(!isBackground)
{
[[UIApplication sharedApplication] endBackgroundTask:isBackground];
isBackground = UIBackgroundTaskInvalid;
break;
}
if(self_terminate)
NSLog(@"background time remaining: %8.2f", [UIApplication sharedApplication].backgroundTimeRemaining);
[NSThread sleepForTimeInterval:2];
}
});
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(@"applicationDidEnterBackground");
[self extendBackgroundRunningTime]; //Call function for upadte time
NSLog(@"Time Remaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
isBackground = NO;
NSLog(@"Enter Foreground");
}
Now application server can send response from Foreground\Background correctly
Result:
