iphone:蓝牙传输
使用的是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/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。