通过BackgroundTask在后台维护多路连接会话?

问题描述 投票:5回答:2

当应用程序暂时在后台进入时,我正在尝试维护MultipeerConnectivity“会话”,所以我考虑使用后台任务,因为我在这里看过几次......问题是我不知道如何“维护”与UIBackgroundTask的会话,有人可以发一个提示

我不关心广告商/浏览器,可以阻止它们,但我希望会话不要断开,因为重新连接是目前的超级错误。

ios ios7 ios8 multipeer-connectivity uibackgroundtask
2个回答
12
投票

根据苹果文档“如果应用程序进入后台,框架将停止广告和浏览并断开任何打开的会话。返回到前台后,框架会自动恢复广告和浏览,但开发人员必须重新建立任何已关闭的会话” Apple doc

扩展连接的一种方法如下

回答我自己的问题,希望能帮助处于相同情况的人们。对于刚接触iOS开发的人来说,“使用后台服务”简单意味着打开目标“功能”选项卡中的“后台模式”选项。仅此一项就可以让你的应用程序在被杀之前在后台生活大约10分钟。

但是,当应用程序进入后台时,我使用“backgroundTimeRemaining”来知道我剩下多少时间,它只是从180开始(以秒为单位,所以3分钟),然而,打印循环确实继续工作三分钟,这意味着需要手动编码达到时间时应该发生的事情。

对于Multipeer Connectivity,这足以在应用程序进入后台时保持连接活动,并且仍然可以毫无问题地接收所有消息/流。

为了稳定起见,我做了一些清洁工作如下:

在appDelegate.h中

@property (nonatomic) UIBackgroundTaskIdentifier backgroundTask; //declaring a background task

在appDelegate.m中

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    self.backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^
                           {
                               //This is called 3 seconds before the time expires
                               //Here: Kill the session, advertisers, nil its delegates,
                               //      which should correctly send a disconnect signal to other peers
                               //      it's important if we want to be able to reconnect later,
                               //      as the MC framework is still buggy
                               [application endBackgroundTask:self.backgroundTask];
                               self.backgroundTask = UIBackgroundTaskInvalid; //Invalidate the background task
                           }];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Here: We should init back the session, start the advertising and set the delegates from scratch
    // This should allow the app to reconnect to the same session with more often than not
    self.backgroundTask = UIBackgroundTaskInvalid; //Here we invalidate the background task if the timer didn't end already
}

1
投票

我在苹果开发者论坛上曾经问过同样的问题。其中一位Apple员工告诉我,当您的应用程序不在前台时,基本上所有的Multipeer连接都应被视为禁区。

© www.soinside.com 2019 - 2024. All rights reserved.