0
votes

I want to make a GroupChat application using Multipeer Connectivity Framework. Al first , I initialize the session by this code

self.peerID =[[MCPeerID alloc] initWithDisplayName:[UIDevice currentDevice].name];
self.session = [[MCSession alloc] initWithPeer:self.peerID];
self.session.delegate  =self;

Then I try to send message with all connected peer devices by this following code.

NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];

if (![self.session sendData:data
                    toPeers:@[self.remotePeers]
                   withMode:MCSessionSendDataReliable
                      error:&error]) {
    NSLog(@"[Error] %@", error);
}

But this gives the following error

 Error Domain=MCSession Code=1 "Peers (
        (
        "iPhone Simulator"
    )
) not connected" UserInfo=0x155e0cc0 {NSLocalizedDescription=Peers (
        (
        "iPhone Simulator"
    )
) not connected}

Here "iPhone Simulator" is the nearby peerDevice. Please Help Me. Thank You.

1

1 Answers

1
votes

You should implement delegate methods for MCSession

#pragma mark - MCSessionDelegate

- (void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state {
NSLog(@"client: status changed to %d for server: %@", state, peerID.displayName);

switch (state) {
    case MCSessionStateNotConnected: {

        [self.servers removeServerItemByPeedID:peerID];
        [self notifyDidChangeServers];
    }
        break;
    case MCSessionStateConnected: {

        if ([self checkPeerIsServer:peerID]) {
            ServerItem *item = [[ServerItem alloc] initWithPeerID:peerID];
            [self.servers singleAddServerItem:item];
            [self notifyDidChangeServers];
        } else {
            NSLog(@" Connected  Client");
        }
    }
        break;
    default:
        break;
}
 NSLog(@"connectedPeers %@", self.session.connectedPeers);
}

- (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID {
NSLog(@"client: received data (len = %lu) from server %@",(unsigned long)[data length], peerID.displayName);

//handle receive data
}

 - (void) session:(MCSession*)session didReceiveCertificate:(NSArray*)certificate fromPeer:(MCPeerID*)peerID certificateHandler:(void (^)(BOOL accept))certificateHandler {
    certificateHandler(YES); 
}

Write me about result, please