Recently a simple understanding of the use of Bluetooth, the approximate step is to connect the device, send data, receive data
1. First import the header file
#import <GameKit/GameKit.h>
2. Set session properties, the session layer required to transfer data
// 保留会话@property (weaknonatomic) GKSession *session;
3, abide by the agent
UINavigationControllerDelegate,UIImagePickerControllerDelegate,GKPeerPickerControllerDelegate
4. Connect the device first
// 1. 创建查找设备的控制器 GKPeerPickerController *ppc = [[GKPeerPickerController alloc] init]; // 2. 设置代理 ppc.delegateself; // 3. 弹出控制器 [ppc show];
5, implement the Agent method, do the operation after successful connection
// 设备连接成功后会调用该方法 peerID:设备节点ID session:会话对象 一旦建立连接之后就会建立会话,然后互相传递数据- (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session{ NSLog(@"%@",peerID); // 设置数据接收着 [self.session setDataReceiveHandler:self withContext:nil]; self.session = session; // 退出查找设备的控制器}
6. Send data
//Send picture- (ibaction) Sendimage: (ID) Sender {if( Self. ImageView. Image) {return; }//Send to specified device//[Self.session senddata:<# (NSData *) #> topeers:<# (Nsarray *) #> withdatamode:<# (GKSendDataMode) # > error:<# (nserror *__autoreleasing *) #>]NSData *data = uiimagepngrepresentation ( Self. ImageView. Image);//Send to so device //gksenddatareliable reliable transmission (data will be communicated, when the network changes, it will reconnect and transmit again)->tcp //Gksenddataunreliable unreliable transmission (data will only be transmitted once, not uploaded to forget it)->udp[ Self. SessionSenddatatoallpeers:data withdatamode:gksenddatareliable Error:Nil];}
7. Receive data
//accept data //data: Received //Peer: Data received from which node //session: Sessions //Context: -(void ) Receivedata: (NSData *) data Frompeer: (nsstring *) Peer insession: (Gksession *) session Context: (void *) context{uiimage *recimage = [uiimage Imagewithdata:data]; self .imageview .image = recimage; Uiimagewritetosavedphotosalbum (recimage, nil , nil , nil ); //Save picture }
8, it should be noted that Gamekit Bluetooth can only be used for the connection between iOS devices, can only be used for the connection between the same application, in fact, more knowledge about Bluetooth, operation is quite complex, here only write a very simple operation.
Easy use of IOS bluetooth