【问题标题】:No response from localhost in iOS Background ModeiOS后台模式下本地主机没有响应
【发布时间】:2019-07-16 09:27:29
【问题描述】:

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

这种情况如下图所示

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

UPD:应用程序已配置为在后台工作

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

【问题讨论】:

标签: ios networking ios-background-mode


【解决方案1】:

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

结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 2015-07-28
    • 2021-11-28
    • 1970-01-01
    • 2019-01-16
    相关资源
    最近更新 更多