当应用程序暂时进入后台时,我试图维护一个 MultipeerConnectivity“ session ”,所以我想使用后台任务,因为我在这里见过几次......问题是我不知道如何“维护”与 UIBackgroundTask 的 session ,有人可以发布提示吗
我不关心广告商/浏览器,可以阻止他们,但我希望 session 不要断开连接,因为目前重新连接非常麻烦。
最佳答案
根据苹果文档“如果应用程序进入后台,框架会停止广告和浏览并断开所有打开的 session 。返回前台后,框架会自动恢复广告和浏览,但开发人员必须重新建立任何关闭的 session ” 引用: 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
}
关于ios - 通过 BackgroundTask 在后台维护多点连接 session ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25801665/