7

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

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

4

2 回答 2

12

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

扩展连接的一种方式如下

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

但是,当应用程序进入后台时,我使用“backgroundTimeRemaining”来知道我还剩下多少时间,它从 180 开始(以秒为单位,所以 3 分钟),然而,打印循环确实继续工作了 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
}
于 2014-09-16T01:37:57.950 回答
2

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

于 2014-09-12T06:05:02.363 回答