使用的是GameKit的框架
遵循协议:<GKPeerPickerControllerDelegate,GKSessionDelegate>
@property (strong, nonatomic) GKSession *currentSession;
@property (strong, nonatomic) GKPeerPickerController *picker;
连接时
picker =[[GKPeerPickerController alloc] init]; picker.delegate = self; picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;//设置成蓝牙的选择(另外一种是ONline的) [picker show];
断开连接
[self.currentSession disconnectFromAllPeers];
currentSession = nil;
发送
NSData *data; NSString *str = [NSString stringWithString:textField.text]; data = [str dataUsingEncoding:NSASCIIStringEncoding]; if (currentSession) { [self.currentSession sendDataToAllPeers:data withDataMode:GKSendDataReliable error:nil]; }
委托方法:
#pragma mark - Delegate //设备连接时 - (void) peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session{ self.currentSession =session;//取得session对象 session.delegate = self; [session setDataReceiveHandler:self withContext:nil]; picker.delegate = nil; [picker dismiss]; } //取消蓝牙选择器 -(void) peerPickerControllerDidCancel:(GKPeerPickerController *)picker{ picker.delegate = nil; } //设备断开连接 - (void) session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state{ switch (state) { case GKPeerStateConnected: NSLog(@"connected"); break; case GKPeerStateDisconnected: NSLog(@"disconnected"); currentSession = nil; default: break; } } //接受数据 - (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context { NSString *str; str = [[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Data received" message:str delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil]; [alert show]; }
本文转自老Zhan博客园博客,原文链接:http://www.cnblogs.com/mybkn/archive/2012/08/10/2631370.html,如需转载请自行联系原作者