更新在使用 Apple 的支持票后,他们确认过于频繁地调用 sendData 并且数据过多会导致断开连接。
我在遇到断点和后台时断开了连接。由于断点不会在应用商店发生,因此您需要在应用即将进入后台时通过启动后台任务来处理后台情况。然后在您的应用返回前台时结束此任务。在 iOS 7 上,这为您提供了大约 3 分钟的背景时间,这总比没有好。
另一种策略是在后台时间到期之前使用 安排本地通知大约 15 秒[[UIApplication sharedApplication] backgroundTimeRemaining]
,这样您就可以在应用程序暂停之前将用户带回应用程序,并且必须关闭多对等框架。也许本地通知会警告他们他们的会话将在 10 秒内到期或什么...
如果后台任务到期,应用程序还在后台,你必须把与多点连接相关的所有东西都拆掉,否则你会崩溃。
- (void) createExpireNotification
{
[self killExpireNotification];
if (self.connectedPeerCount != 0) // if peers connected, setup kill switch
{
NSTimeInterval gracePeriod = 20.0f;
// create notification that will get the user back into the app when the background process time is about to expire
NSTimeInterval msgTime = UIApplication.sharedApplication.backgroundTimeRemaining - gracePeriod;
UILocalNotification* n = [[UILocalNotification alloc] init];
self.expireNotification = n;
self.expireNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:msgTime];
self.expireNotification.alertBody = TR(@"Text_MultiPeerIsAboutToExpire");
self.expireNotification.soundName = UILocalNotificationDefaultSoundName;
self.expireNotification.applicationIconBadgeNumber = 1;
[UIApplication.sharedApplication scheduleLocalNotification:self.expireNotification];
}
}
- (void) killExpireNotification
{
if (self.expireNotification != nil)
{
[UIApplication.sharedApplication cancelLocalNotification:self.expireNotification];
self.expireNotification = nil;
}
}
- (void) applicationWillEnterBackground
{
self.taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^
{
[self shutdownMultiPeerStuff];
[[UIApplication sharedApplication] endBackgroundTask:self.taskId];
self.taskId = UIBackgroundTaskInvalid;
}];
[self createExpireNotification];
}
- (void) applicationWillEnterForeground
{
[self killExpireNotification];
if (self.taskId != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:self.taskId];
self.taskId = UIBackgroundTaskInvalid;
}
}
- (void) applicationWillTerminate
{
[self killExpireNotification];
[self stop]; // shutdown multi-peer
}
由于 Apple 错误,您还需要在 MCSession 委托中使用此处理程序:
- (void) session:(MCSession*)session didReceiveCertificate:(NSArray*)certificate fromPeer:(MCPeerID*)peerID certificateHandler:(void (^)(BOOL accept))certificateHandler
{
if (certificateHandler != nil) { certificateHandler(YES); }
}