I want to transfer NSString
between two iOS device, via bluetooth. Can anybody please help how to do transfer NSString
via bluetooth? I searched for sp
I'm going to comment more extensively on how you can use MCSession
for this sort of simple case since when I was first familiarizing myself with MCSession
, I was amazed at how little information was available on how to utilize a simple MCSession
without adding the extra layer of an MCBrowserViewController
.
In your .h, add the following delegates: MCSessionDelegate
, MCNearbyServiceAdvertiserDelegate
, and MCNearbyServiceBrowserDelegate
. Also declare class instance variables for MCPeerID *devicePeerID
, MCSession *session
, MCNearbyServiceAdvertiser *serviceAdvertiser
, and MCNearbyServiceBrowser *nearbyServiceBrowser
.
In your .m, during viewDidLoad or any other time before you wish to start your MCSession
, initialize your MCPeerID
:
devicePeerId = [[MCPeerID alloc] initWithDisplayName:DISPLAY_NAME];
Then use that MCPeerID
to initialize the MCSession
:
session = [[MCSession alloc] initWithPeer:devicePeerId securityIdentity:nil encryptionPreference:MCEncryptionNone];
session.delegate = self;
Now, in order to avoid using the MCBrowserViewController
, you have to init your own MCNearbyServiceAdvertiser
to allow your device to advertise a session, MCNearbyServiceBrowser
to allow your device to find a session, or you can even init BOTH on the same device to allow for simultaneous advertising and browsing:
serviceAdvertiser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:myDevicePeerId discoveryInfo:nil serviceType:SERVICE_TYPE];
serviceAdvertiser.delegate = self;
// (I've set discoveryInfo to nil here, but it can also contain an NSDictionary of data to pass along to browsers who find this advertiser via the browser:foundPeer:withDiscoveryInfo method)
nearbyServiceBrowser = [[MCNearbyServiceBrowser alloc] initWithPeer:myDevicePeerId serviceType:SERVICE_TYPE];
nearbyServiceBrowser.delegate = self;
Next, if you've set the device as an advertiser, you need to implement the MCNearbyServiceAdvertiserDelegate
methods.
To field invitations from browsing peers:
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void (^)(BOOL, MCSession *))invitationHandler {
NSLog(@"invitation received");
if (want_to_accept_invitation)
invitationHandler(YES, session);
else
invitationHandler(NO, session);
}
To receive an error if the device has yet to start advertising for some reason:
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didNotStartAdvertisingPeer:(NSError *)error {
NSLog(@"Did not start advertising error: %@", error);
}
Likewise, if you've set the device as a browser, you need to implement the MCNearbyServiceBrowserDelegate
Methods:
// Peer found
- (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info {
NSLog(@"Session Manager found peer: %@", peerID);
if (want_to_connect)
[serviceBrowser invitePeer:peerID toSession:session withContext:nil timeout:CONNECTION_TIMEOUT];
}
// Peer lost, ex. out of range
- (void)browser:(MCNearbyServiceBrowser *)browser lostPeer:(MCPeerID *)peerID {
NSLog(@"Session Manager lost peer: %@", peerID);
}
- (void)browser:(MCNearbyServiceBrowser *)browser didNotStartBrowsingForPeers:(NSError *)error {
NSLog(@"Did not start browsing for peers: %@", error);
}
Then you need the MCSessionDelegate
Methods to help notify the user of changing connection states and facilitate the sending and receiving of data:
- (void)session:(MCSession *)session didReceiveCertificate:(NSArray *)certificate fromPeer:(MCPeerID *)peerID certificateHandler:(void (^)(BOOL accept))certificateHandler {
NSLog(@"Did receive certificate");
certificateHandler(true);
}
// To detect changes in the state of your connections with your peers….
- (void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state {
switch (state) {
case MCSessionStateConnected: {
NSLog(@"Connected to %@", peerID);
// If you'd like to send your text string as soon as you're connected...
NSError *error;
[session sendData:[@"text" dataUsingEncoding:NSUTF8StringEncoding] toPeers:[NSArray arrayWithObject:peerID] withMode:MCSessionSendDataReliable error:&error];
break;
} case MCSessionStateConnecting: {
NSLog(@"Connecting to %@", peerID);
break;
} case MCSessionStateNotConnected: {
break;
}
}
}
- (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID {
NSLog(@"Did receive data.");
/// Receive the string here.
NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
Note that to send the data, I've used:
[session sendData:[@"text" dataUsingEncoding:NSUTF8StringEncoding] toPeers:[NSArray arrayWithObject:peerID] withMode:MCSessionSendDataReliable error:&error];
to transmit the data as soon as the user's connected with his peers. But this line can be used to send data elsewhere in the code, ex:
- (void)sendMessageToAllPeers:(NSString *)message {
[session sendData:[message dataUsingEncoding:NSUTF8StringEncoding] toPeers:session.connectedPeers withMode:MCSessionSendDataReliable error:&error];
}
- (void)sendMessage:(NSString *)message toPeerIDs:(NSArray *)peerIDs {
[session sendData:[message dataUsingEncoding:NSUTF8StringEncoding] toPeers:peerIDs withMode:MCSessionSendDataReliable error:&error];
}
Finally, to start/stop advertising your advertiser and/or browser, you can call [_serviceAdvertiser start/stopAdvertisingPeer]
, [_nearbyServiceBrowser start/stopBrowsingForPeers]
:
- (void)start {
[serviceAdvertiser startAdvertisingPeer];
[nearbyServiceBrowser startBrowsingForPeers];
}
- (void)stop {
[serviceAdvertiser stopAdvertisingPeer];
[nearbyServiceBrowser stopBrowsingForPeers];
}
There are other methods, but these are the basics. Wrote this out fairly quickly though, so anyone should feel free to amend!
Check the source code of Apple developer forum for BTLE Transfer
I hope this will helps you to transfer string or any data from one device to another using bluetooth.