iOS 后台模式下本地主机无响应

No response from localhost in iOS Background Mode

应用程序在 iOS 移动设备 (iPhone\iPad) 本地服务器 localhost:25989 上运行,当转到浏览器时,我们发送一些请求 http://localhost:25989 但是在我们 return 到应用程序之前,服务器(应用程序)不会发送响应。

这种情况如下图所示

UPD:应用程序已配置为在后台运行

问题:如何组织在后台模式下工作的应用程序代码,服务器可以return回答localhost:25989?

注意:iOS 13+ 的代码已损坏,许多部分现已被 Apple 弃用。 BGTaskSheduler new class 替换 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的响应

结果: