Friday, May 20, 2011

iOS Bluetooth Programming - Getting devices to see each other

Sometime back, I wrote an article for on how to write Bluetooth iPhone applications. In that article, iOS devices running that program will be able to see each other when you use the GKPeerPickerController class to look for each other. So why is it that your application can only see another device running the same application, and not other Bluetooth applications running on the same device?

The reason is simple. When you use the GKPeerPickerController class to look for other Bluetooth devices, it creates a session ID. Applications will only be able to see each other if the session IDs are identical. By default, the session ID is the application's Bundle Identifier (you can see this in the Info.plist file in your Xcode project. Hence, if an application is installed on two devices, one should be able to see the other since they have the same Bundle Identifier. By default, the bundle identifier is set to: com.yourcompany.${PRODUCT_NAME:rfc1034identifier}. So if two applications have different Product Name they won't be able to see each other.

But what if you want to customize the session ID by creating your own? To do so, you just need to implement the following method:
- (GKSession *)peerPickerController:(GKPeerPickerController *)picker
sessionForConnectionType:(GKPeerPickerConnectionType)type {
if (!self.currentSession) {
self.currentSession = [[[GKSession alloc] initWithSessionID:@"Session_ID_Here" displayName:nil sessionMode:GKSessionModePeer] autorelease];
self.currentSession.delegate = self;
return self.currentSession;
In this case, devices can only see each other if their session ID are the same. The displayName argument allows you to specify the name of the device that will be seen by the other party. If you set it to nil, iOS will use the device's name.

No comments: