【问题标题】:Maintain a Multipeer Connectivity session in Background via BackgroundTask?通过 BackgroundTask 在后台维护多点连接会话?
【发布时间】:2014-11-06 05:48:19
【问题描述】:

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

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

【问题讨论】:

  • 看看这段代码。 github.com/davidkaminsky/Unplugged/blob/master/Unplugged/… 我遇到了 TCP 连接的问题,您可以让您的应用程序在后台运行几分钟,但如果更长,您应该清理连接并停止后台任务。纯粹使用它来在用户短时间内离开您的应用时保持连接打开。
  • 谢谢,我最终做了一些类似的事情,但没那么花哨(即不监控电池寿命)。

标签: ios ios7 ios8 multipeer-connectivity uibackgroundtask


【解决方案1】:

根据苹果文档“如果应用程序进入后台,框架会停止广告和浏览并断开所有打开的会话。返回前台后,框架会自动恢复广告和浏览,但开发人员必须重新建立任何关闭的会话" 参考: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
}

【讨论】:

  • 这不是真的,也不起作用。一旦我将应用程序置于后台,我的会话立即停止工作,而不是在 10 分钟后,甚至在 1 分钟后......我所有的同行都断开了连接。
【解决方案2】:

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

【讨论】:

  • 是的,一般未记录的规则是 MC 不应该在后台工作......我仍然不确定这是否是“规则”(例如应用程序将被应用商店拒绝如果是这样),或者只是由于其他原因(层限制、CPU 使用率等)而不受支持。目前,我将它用于企业应用程序,所以只要它没有错误/崩溃就没有关​​系。
  • @Einho 当您说您使用的是企业应用程序时,这是否意味着您已经完全绕过了时间限制? IE。您能否让 MC 在后台运行超过 10 分钟?
猜你喜欢
  • 2013-02-04
  • 1970-01-01
  • 2016-11-04
  • 1970-01-01
  • 2019-08-16
  • 2011-11-05
  • 2010-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多