subject: Bluetooth With Iphones - Iphone Bluetooth Compatibility [print this page] iPhone application will allow us to do Communication between devices using Bluetooth technology.
In iPhone SDK, it is possible to connect two iOS devices and to share data between them using bluetooth programmatically. There are following options available
GameKit framework(iOS 3.0 and later)
Bump API
Bonjour networking
GameKit, the name suggests that it has been made for games but it can be used for other purposes too. It provides peer-to-peer connectivity between iOS devices. Everything is set up for you and you can send data between two devices in a few lines of code.
iPhone Canada, learn how can share data between two devices using bluetooth in Game kit.
1.First create a project named Bluetooth. Now, you need to import the GameKit framework to your project.
2.In the ViewController.h file, import GameKit framework and declare the following objects and actions,
#import
#import
@interface ViewController : UIViewController
{
GKSession *currentSession;
GKPeerPickerController *pickerController;
IBOutlet UIButton *connectButton;
IBOutlet UIButton *disconnectButton;
}
-(IBAction)connectButtonClicked:(id)sender;
-(IBAction)disconnectButtonClicked:(id)sender;
The GKSession object is used to represent a session between two connected Bluetooth devices. It will be used when you will send and receive data between the two devices.
The GKPeerPickerController class provides a standard UI to let application discover, select and connect to another Bluetooth device.
3.Add following code in the ViewController.m file.
4.When you has connected to the peer Bluetooth device, save the GKSession object to the currentSession object. It is used when you will share data with connected device. Add method for disconnecting devices,
-(IBAction)disconnectButtonClicked:(id)sender
{
connectButton.hidden=FALSE;
disconnectButton.hidden=TRUE;
[ currentSession disconnectFromAllPeers];
currentSession=nil;
}
We establish the connection between devices. Now sending and receiving data between connected devices:
5.Add following action in the ViewController.h file.
-(IBAction) sendButtonClicked:(id) sender
{
//--- NSString object to NSData---
NSData* data;
NSString *string = [NSString stringWithString:@"Data from iPhone via bluetooth"];
data = [string dataUsingEncoding: NSASCIIStringEncoding];
SendDatatoAllPeers method of GKSession is used for sending data to peer device.
6.You are now ready to test the application. For testing this application, we at iPhone USassume you have two devices or simulator and a device. Once the application is deployed to the two devices, launch the application on both devices. On each device, tap the Connect button. The GKPeerPickerController will display the standard UI to discover other devices. Once you discovered a device, connect to it and share data between them.