Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multipeer connectivity disconnects on background

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,

like image 209
Legolas Avatar asked Jul 14 '14 21:07

Legolas


1 Answers

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.

like image 109
ChrisH Avatar answered Sep 19 '22 01:09

ChrisH