0

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

这种情况如下图所示

  • 活动 - 我的 iOS 应用程序前台(服务器)
  • 背景 -在任何浏览器(Safari、Chrome 等)中向我的 iOS 应用程序背景发送请求

在此处输入图像描述

UPD:应用程序已配置为在后台工作 在此处输入图像描述

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

4

1 回答 1

0

注意: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 发送响应

结果在此处输入图像描述

于 2019-07-17T13:28:00.923 回答