该应用程序在localhost:25989上的iOS移动设备(iPhone \ iPad)本地服务器上运行,当转到浏览器时,我们发送了一些请求http://localhost:25989,但是服务器(应用程序)在以下情况下不会发送响应:我们返回到应用程序。
这种情况显示在下面的图片中
问题:如何组织在后台模式下服务器可以从localhost:25989返回答案的应用程序代码?
答案 0 :(得分:0)
我解决了问题,方法是在我的 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发送响应