So, my ideal scenario is that I want my MCNearbyServiceAdvertiser
and MCNearbyServiceBrowser
to work in the background. But I understand that these need to be killed when application resign active, and resume the work when i come back to foreground.
But what is bugging me is that, when i CONNECT two peers to a session, and start chatting between them, it suddenly disconnects. Meaning.. my MCSession object disconnects when it goes to background. I was also told of the Apple bug with certificateHandler(YES);
, and i explicitly call it now.
I want to set this up exactly how FIRECHAT
does it. Can anyone give me some pointers on why its keeps failing, or how you guys manage to keep this active?
Thanks,
In order to for your peers to stay connected you need to start a background task when the app enters the background, otherwise iOS will tear down the network connections and suspend the app.
- (void)applicationDidEnterBackground:(UIApplication *)application {
//Start a background task to keep the app running in the background
self.bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
//If your background task takes too long, this block of code will execute
[self cleanUp];
self.bgTask = UIBackgroundTaskInvalid;
}];
//Do the work you need to do
dispatch_async(dispatch_get_main_queue(), ^{
//Finish up the transfer of data between peers
[self cleanUp];
//End the background task so that iOS doesn't kill the app
[application endBackgroundTask:_bgTask];
});
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
[application endBackgroundTask:_bgTask];
}
- (void)cleanUp {
//Clean up the Multipeer session
}
Note that this only applies to existing connections that have been made while the app was in the foreground. You still have to stop the browsing and advertising when entering background.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With