Search code examples
iosmultipeer-connectivity

iOS Multipeer Connectivity - Showing DiscoveryInfo in a custom MCNearbyServiceBrowser


Any help for implementing this scenario would be appreciated.

  1. My "Advertiser" peer needs to send a short text as a DiscoveryInfo.

  2. And then "Browser" peer would show DisplayName and DiscoveryInfo of all available advertisers in a table.

I have written a custom SessionContainer and it works but I have no ides that how I can send DiscoveryInfo by advertiser and display it in browser peer. (I am using MCNearbyServiceBrowser)

Any help would be appreciated!


Solution

  • MCBrowserViewController provides a standard user interface that allows the user to choose nearby peers to add to a session.

    If you want a customised browser, you should use MCNearbyServiceBrowser. This lets your app search programmatically for nearby devices with apps that support sessions of a particular type (that you specify).

    Creation of the browser looks like this:

    self.thisPeer = [[MCPeerID alloc] initWithDisplayName:@"Peer Name"];
    self.session = [[MCSession alloc] initWithPeer:self.thisPeer ];
    self.session.delegate = self;
    
    self.serviceBrowser = [[MCNearbyServiceBrowser alloc] initWithPeer:self.thisPeer serviceType:<lowercase 1-15 chars>
    self.serviceBrowser.delegate = self;
    [self.serviceBrowser startBrowsingForPeers];
    

    Creation of the advertiser looks like this:

    NSString *deviceName = [[UIDevice currentDevice] name];
    MCPeerID *peerID = [[MCPeerID alloc] initWithDisplayName:deviceName];
    self.session = [[MCSession alloc] initWithPeer:peerID];
    self.session.delegate = self;
    
    NSMutableDictionary *info = [NSMutableDictionary dictionaryWithObject:@"other info" forKey:@"peerInfo"];
    self.advertiser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:peerID discoveryInfo:info serviceType:<same service name as browser>];
    self.advertiser.delegate = self;
    [self.advertiser startAdvertisingPeer];
    

    When the browser hears the nearby peer its delegate method is called:

    - (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info {
        NSLog(@"Found a nearby advertising peer %@ withDiscoveryInfo %@", peerID, info);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"peerConnectionChanged" object:info];
    }
    

    Here you might perhaps post a notification that your table view controller can listener for. Your UITableView can then show any info included in the discoveryInfo dictionary. Note that you will need to switch to the main thread to update the UI

    When you are ready to invite the peer to join the session you would call

    [self.serviceBrowser invitePeer:peerID toSession:self.session withContext:nil timeout:30];