注意:iOS 13+ 的代码已损坏,许多部分现已被 Apple 弃用。BGTaskSheduler 新类替换 UIBackground。
我解决了我的问题,通过在我的AppDelegate.m文件中使用以下代码来保持服务器在后台运行:
...
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");
}
现在应用程序服务器可以正确地从 Foreground\Background 发送响应
结果:
