multipeer1

Hey Folks,

I have been recently exploring the Multipeer connectivity framework iOS and i thought sharing the same would be really helpful for those who have unexplored this framework.

Well First things first. Few questions & answers :

  • Why use Multipeer connectivity ?
    • If you are looking forward for connecting two or more iPhones via bluetooth or wifi and that need file sharing or needs something like chat application, you are on right track
  • What is Multipeer ?
    • Multipeer framework is build for iPhone to connect peripheral devices, We can use it to connect to iPhones, iWatch, iBeacons and other bluetooth accessories too. Its basic framework that defines protocol for peer to peer connections

Enough talking, lets dig into coding part.

Pre-requisite for implementing peer to peer connectivity.

  • iPhone (Physical Device)
  • Simulator OR another iPhone or Bluetooth peripheral devices
  • Basic overview of Peer commands and full understanding of sending bytes in packets through encryptions. (Lolz just kidding)

So lets Start.

Step 1 : Add Multipeer Connectivity Framework

Screen Shot 2016-06-17 at 9.10.09 PM

Step 2 : Create two files Master & Slave

Also download Multipeer this 2 files

Master would be searching for another device & slave would advertise itself that i am available for connection. (Same like Groom/Bride Searching :P).

So here is code for Master :

#import <MultipeerConnectivity/MultipeerConnectivity.h>
@import MultipeerConnectivity;
@interface MasterVC : UIViewController <MCBrowserViewControllerDelegate>
- (IBAction)browseForDevices:(id)sender;
@end

For Master.m

// in your appdelegate

@property (nonatomic, strong) MPManager *mpManager;

_mpManager = [[MPManager alloc] init];

// In your master.m

- (IBAction)browseForDevices:(id)sender {
    [[_appDelegate mpManager] setupMCBrowser];
    [[[_appDelegate mpManager] browser] setDelegate:self];
    [self presentViewController:[[_appDelegate mpManager] browser] animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didStartReceivingResourceWithNotification:)
                                                 name:@"MCDidStartReceivingResourceNotification"
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updateReceivingProgressWithNotification:)
                                                 name:@"MCReceivingProgressNotification"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didFinishReceivingResourceWithNotification:)
                                                 name:@"didFinishReceivingResourceNotification"
                                               object:nil];
}

#pragma mark - Public method implementation

- (IBAction)browseForDevices:(id)sender {
    [[_appDelegate mpManager] setupMCBrowser];
    [[[_appDelegate mpManager] browser] setDelegate:self];
    [self presentViewController:[[_appDelegate mpManager] browser] animated:YES completion:nil];
}


#pragma mark - MCBrowserViewControllerDelegate method implementation

-(void)browserViewControllerDidFinish:(MCBrowserViewController *)browserViewController{
    [_appDelegate.mpManager.browser dismissViewControllerAnimated:YES completion:nil];
    [_tblConnectedDevices reloadData];
}


-(void)browserViewControllerWasCancelled:(MCBrowserViewController *)browserViewController{
    [_appDelegate.mpManager.browser dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Private method implementation

-(void)peerDidChangeStateWithNotification:(NSNotification *)notification{
    MCPeerID *peerID = [[notification userInfo] objectForKey:@"peerID"];
    NSString *peerDisplayName = peerID.displayName;
    MCSessionState state = [[[notification userInfo] objectForKey:@"state"] intValue];
    
    if (state != MCSessionStateConnecting) {
        if (state == MCSessionStateConnected) {
            [_arrConnectedDevices addObject:peerDisplayName];
        }
        else if (state == MCSessionStateNotConnected){
            if ([_arrConnectedDevices count] > 0) {
                @try {
                    int indexOfPeer = [_arrConnectedDevices indexOfObject:peerDisplayName];
                    [_arrConnectedDevices removeObjectAtIndex:indexOfPeer];
                } @catch (NSException *exception) {
                    
                } @finally {
                    
                }
                
            }
        }
        [_tblConnectedDevices reloadData];
        
        BOOL peersExist = ([[_appDelegate.mpManager.session connectedPeers] count] == 0);
    }
}

And For Slave

- (void)viewDidLoad {
    [super viewDidLoad];
    _appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [[_appDelegate mpManager] setupPeerAndSessionWithDisplayName:[UIDevice currentDevice].name];
    [[_appDelegate mpManager] advertiseSelf:YES];
}

-(void)didStartReceivingResourceWithNotification:(NSNotification *)notification{


}
-(void)didFinishReceivingResourceWithNotification:(NSNotification *)notification{

}

Step 3 : Send Data to Slave Device

NSData *dataToSend = [@"play" dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *allPeers = _appDelegate.mpManager.session.connectedPeers;
    NSError *error;
    
    [_appDelegate.mpManager.session sendData:dataToSend
                                     toPeers:allPeers
                                    withMode:MCSessionSendDataReliable
                                       error:&error];

Step 4 : Test & Debug :)

Happy Multipeering. Feel free to contact me.

Multipeer Connectivity in iOS

Aadil Keshwani

People call me geek i call myself Coder. I like to explore & learn new things, R&D and Innovation motivates me. By profession i am iPhone Developer but i have sound knowledge of PhoneGap, HTML, CSS3, WordPress, Photoshop, PHP, CodeIgniter, OpenCart. Feel free to contact me for any queries or help in above technologies, i would be more than happy to help you out.

Category: Uncategorized
983 views