ios7中的Multipeer Connectivity中的消息发送失败

时间:2015-02-17 04:58:29

标签: ios iphone ios-simulator ios7.1 multipeer-connectivity

我想使用Multipeer Connectivity Framework创建一个GroupChat应用程序。 首先,我通过此代码初始化会话

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

然后我尝试通过以下代码向所有连接的对等设备发送消息。

NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];

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

但这会产生以下错误

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

这里" iPhone模拟器"是附近的peerDevice。 请帮我。谢谢。

1 个答案:

答案 0 :(得分:1)

您应该为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); 
}

请告诉我结果,