Search code examples
iosobjective-ccocoabonjourmultipeer-connectivity

Why does Multi Peer Connectivity only work with MCAdvertiserAssistant and not MCNearbyServiceAdvertiser


I followed this tutorial on MultiPeerConnectivity (MCF) and list most tutorials online, they took the shortcut of using the services of MCAdvertiserAssistant and MCBrowserViewController

I tried implementing the same tutorial but with using MCNearbyServiceAdvertiser and MCNearbyServiceBrowser instead because i'm interested in customizing the discoverability on my app.

things work fine as far as listing the nearby devices.. but then the trouble starts in the MCNearbyServiceAdvertiserDelegate where I call this method:

- (void)           advertiser:(MCNearbyServiceAdvertiser *)advertiser
 didReceiveInvitationFromPeer:(MCPeerID *)peerID
                  withContext:(NSData *)context
            invitationHandler:(void (^)(BOOL, MCSession *))invitationHandler {

    // Allow the peer to join this Vibereel
    MCSession *peerSession = [[MCSession alloc] initWithPeer:_peerID];
    peerSession.delegate = self;
    invitationHandler(YES, peerSession);
    NSLog(@"Accepted entry request for peer %@", [peerID displayName]);
}

this does not trigger the did change state method:

-(void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state

although it did with the original versions.

I know I obviously need to put more code to demonstrate the problem.. and so I created a github repo that started with the original code. This is the commit that adds the custom made browser along with the custom UITableViewController to display nearby devices (works fine) and here is the commit that does the advertising (doesn't work)


Solution

  • Make the peerSession a property of the class instead of a local variable of the method. The problem is that in your code the peerSession is released at the end of the method. I have a working example on my blog.