Multipeer Connectivity is a framework that enables nearby devices to communicate over Wi-Fi networks, P2P Wi-Fi, and Bluetooth personal lans. Linked nodes can securely transfer information, streams, or other file resources.
In my opinion, its function is very similar to iOS\MacOS AirDrop, and its flying efficiency is really sour.
Without further ado, let’s integrate the functions of MultipeerConnectivity. First, introduce the system framework
#import Copy the code
Declare the following properties in turn, with detailed remarks here.
*/ @property (nonatomic,strong)MCPeerID * peerID; /** * Data flow, enabling and managing communication between all people in a Multipeer connection session. Sending data to other people via Sesion. Similar to Scoket */ @property (nonatomic,strong)MCSession * session; /** * can receive and process the user's response to request a connection. There is no callback, the default prompt box will pop up and the connection will be processed. */ @property (nonatomic,strong)MCAdvertiserAssistant * advertiser; /** * Is used to search for nearby users and invite them to join a session. */ @property (nonatomic,strong)MCNearbyServiceBrowser * brower; /** * list of users */ @property (nonatomic,strong)MCBrowserViewController * browserViewController; / / @property (nonatomic,strong)NSMutableArray * sessionArray;Copy the code
Next we initialize the current device and enable search for nearby users.
/** * Connection Settings */ - (void)createMC{// Get device name NSString * name = [UIDevice currentDevice]. Name; // user _peerID = [[MCPeerID alloc]initWithDisplayName:name]; _session = [[MCSession alloc]initWithPeer:_peerID]; // Set the delegate _session.delegate = self; // Set the Broadcast service (sender) _advertiser = [[MCAdvertiserAssistant alloc]initWithServiceType:@"type" discoveryInfo:nil session:_session]; // Start broadcasting [_advertiser start]; // Set the discovery service (receiver) _brower = [[MCNearbyServiceBrowser alloc]initWithPeer:_peerID serviceType:@"type"]; // Set the delegate to _brower.delegate = self; [_brower startBrowsingForPeers]; }Copy the code
Don’t forget to add their agreement here, the following MCSessionDelegate, MCBrowserViewControllerDelegate, MCNearbyServiceBrowserDelegate. Finally, the corresponding proxy method can be implemented
#pragma MC related proxy method /** * Finds nearby users ** @param Browser searches nearby users * @param peerID nearby users * @param info details */ - (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info{ NSLog(@" find nearby user %@", peerid.displayName); if (_browserViewController == nil) { _browserViewController = [[MCBrowserViewController alloc]initWithServiceType:@"type" session:_session]; _browserViewController.delegate = self; / / [self presentViewController:_browserViewController animated:YES completion:nil]; }} /** * a nearby user disappears ** @param browser searches for nearby users * @param peerID user */ - (void)browser:(MCNearbyServiceBrowser *)browser LostPeer :(MCPeerID *)peerID{NSLog(@" nearby user %@ left ", peerid.displayname); } #pragma mark BrowserViewController selects the corresponding user ** @param BrowserViewController user list */ - (void)browserViewControllerDidFinish:(MCBrowserViewController *)browserViewController{ [self dismissViewControllerAnimated:YES completion:nil]; _browserViewController = nil; // Close the broadcast service to stop other people finding [_advertiser stop]; } /** * User list closes ** @param browserViewController User list */ - (void)browserViewControllerWasCancelled:(MCBrowserViewController *)browserViewController{ [self dismissViewControllerAnimated:YES completion:nil]; _browserViewController = nil; [_advertiser stop]; } #pragma mark MCSession proxy method /** * stores when a connection state change is detected ** @param session MC stream * @param peerID user * @param state Connection state */ - (void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state{// check if the connection is if (state == MCSessionStateConnected) {// Save the connection if (! [_sessionArray containsObject:session]) {// If there is no save [_sessionArray addObject:session]; }}} /** * received messages ** @param session MC stream * @param data incoming binary data * @param peerID user */ - (void)session:(MCSession) *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID{ NSString * message = [NSString stringWithFormat:@"%@:%@",peerID.displayName,[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]]; dispatch_async(dispatch_get_main_queue(), ^{ [_dataArray addObject:message]; NSIndexPath * indexPath = [NSIndexPath indexPathForRow:_dataArray.count - 1 inSection:0]; [_tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop]; [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES]; }); } /** * receive data stream ** @param session MC stream * @param stream data stream * @param streamName Data stream name (identifier) * @param peerID User */ - (void)session:(MCSession *)session didReceiveStream:(NSInputStream *)stream withName:(NSString *)streamName FromPeer :(MCPeerID *)peerID{} /** * starts receiving resources */ - (void)session:(MCSession *)session didStartReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID withProgress:(NSProgress * * * *) progress {} / resources receiving end * / - (void) session: (MCSession *) session didFinishReceivingResourceWithName: (nsstrings *)resourceName fromPeer:(MCPeerID *)peerID atURL:(NSURL *)localURL withError:(NSError *)error{ }Copy the code
The renderings are as follows
Click Done to complete the connection. The proxy method has the flow of listening on nearby devices, connecting, receiving and so on. For sending data, you can simply set up a page. Such as when textField hits Return. There are two types of data to be sent, namely UDP and TCP in the socket.
- (BOOL)textFieldShouldReturn:(UITextField *)textField{if (textfield.text.length > 0) {/** * two types MCSessionSendDataUnreliable is similar to the UDP connections MCSessionSendDataReliable similar to TCP connection way * / [_session sendData publishes the event: [textField. Text dataUsingEncoding:NSUTF8StringEncoding] toPeers:_session.connectedPeers withMode:MCSessionSendDataUnreliable error:nil]; //UI operation [_dataArray addObject: textfield.text]; NSIndexPath * indexPath = [NSIndexPath indexPathForRow:_dataArray.count - 1 inSection:0]; [_tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop]; [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES]; } return YES; }Copy the code
rendering
Here you can use two devices, simulator and real machine. When one of the devices detects nearby devices, it will pop up the list of nearby devices and click select to carry out communication operation. The use case simulates sending a string, which can also be replaced with a file, since both are passed in binary. I’m sure you’ll notice its flying speed, and that’s it.
Demo Download link
IOS forgotten near field communication tool Demo 🔗