TAGS :Viewed: 5 - Published at: a few seconds ago

[ History of previously connected bluetooth devices using MCNearbyServiceBrowser ]

I'm using MCNearbyServiceBrowser to discover nearby bluetooth devices & inviting using invitePeer: toSession: withContext: timeout:.

Now the problem is that i want to keep history of all connected devices & re-connect them in future (manually by clicking them in UITableview) if the are nearby again. Is this possible? And is it compatible according to Apple's policy? Thanks.

UPDATE:

I already achieved the goal as "jamdaddy25" answered (before he answered :P) & it's working fine too.. But what if two devices have the same name? In that case it will be a problem of not showing one of the two or more devices in the list. And i don't want that. BTW thanks for response.

Answer 1


You could keep the peerID display name. This is a property on MCPeerID. When you have started browsing, either prior to user selecting a previously connected peer or starting up browsing upon coming to that screen, cycle through the nearby peers and see if u have a display name match. If so, you can systematically send an invite and reestablish the connection.

You could even do this so the only selectable previous connections are those which are currently nearby peers.

Update: So to make sure that you don't have peer name collisions you need to make the names unique. The best way I know how to do this is to create a UUID based name. I save this inside of a simple object (UserPeerInfo below) and saving / load this to NSUserDefaults so this peer name will be used always for this peer

// Initialize with any stored data
if (!_userPeerInfo) {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"userPeerInfo"]) {
        NSData *userPeerInfoData = [defaults objectForKey:@"userPeerInfo"];
        _userPeerInfo = (UserPeerInfo*)[NSKeyedUnarchiver unarchiveObjectWithData:userPeerInfoData];
    } else
    {
        NSString *peerName = [[NSUUID UUID] UUIDString];
        _userPeerInfo.peerName = peerName;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        // Create an NSData representation
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_userPeerInfo];
        [defaults setObject:data forKey:@"userPeerInfo"];
        [defaults synchronize];
    }
}

Then when setting the name of your peer and initializing, use that peer name like normal

self.peerId = [[MCPeerID alloc] initWithDisplayName:self.userPeerInfo.peerName];
self.advertiser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:self.peerId discoveryInfo:info serviceType:kServiceType];
self.advertiser.delegate = self;
[self.advertiser startAdvertisingPeer];