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

我试图保持一个MultipeerConnectivity“会话”,当应用程序暂时进入后台,所以我想使用一个后台任务,因为我在这里看过几次…问题是我不知道如何“维护”与UIBackgroundTask会议,可以有人请张贴

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

回答我自己的问题,希望能够帮助那些处于同样状况的人。 对于iOS开发新手来说,“使用后台服务”的简单方法是打开目标的“function”选项卡中的“背景模式”选项。 只有这一点,应该可以让你的应用程序在被杀之前在背景中保持10分钟的生命。

但是,当应用程序转到后台时,我使用“backgroundTimeRemaining”来知道我已经离开了多less时间,它从180(以秒为单位,3分钟)开始,然而,打印循环继续工作,通过了三分钟这意味着需要手动编码在到达时间后应该发生什么。

对于Multipeer Connectivity,这足以在应用程序进入后台时维持连接,并且仍然可以接收所有消息/数据stream。

为了稳定,我做了一些清理,如下所示:

在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 } 

我在苹果开发者论坛上曾经问过这个相同的问题。 其中一位苹果员工告诉我,当你的应用程序不在前台时,基本上所有的Multipeer连接都应该被认为是禁止的。