开发者

Problem About Sending Text via Peer to Peer Networking in iPhone

I'm trying to send some text via Peer to Peer Networking in iPhone. I've modified the GKTank Sample a little to make it send string instead of customized struct data. The following is the code I've written. My problem is that I can send @"hello" to another ios device and it can receive a data (length 5), but the NSData it received cannot be converted to NSString so the received data cannot show as a string. Any ideas about what's wrong with the code?

- (void)receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void *)context 
{
    NSString *recvStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    textField.text = recvStr;
    [recvStr release];
}

- (void)sendNetworkPacket:(GKSession *)session packetID:(int)packetID withData:(void *)data ofLength:(int)length reliable:(BOOL)howtosend开发者_开发技巧
{
    NSData *packet = [NSData dataWithBytes:data length:length];
    NSError *error = nil;
    if(howtosend == YES) { 
        [session sendData:packet toPeers:[NSArray arrayWithObject:gamePeerId] withDataMode:GKSendDataReliable error:&error];
    } else {
        [session sendData:packet toPeers:[NSArray arrayWithObject:gamePeerId] withDataMode:GKSendDataUnreliable error:&error];
    }
    if (!error) {
        NSLog(@"Did send data");
    } else {
        NSLog(@"Send data failed: %@", [error localizedDescription]);
    }

}

- (IBAction)sendText:(id)sender
{
    if (self.gameSession && textField.text.length) {
        NSData *data = [textField.text dataUsingEncoding:NSUTF8StringEncoding];
        [self sendNetworkPacket:gameSession packetID:0 withData:data ofLength:[data length] reliable:NO];
    }
}


The problem is solved by type cast NSData* to char* and use -stringWithCString:encoding: to get NSString from CString.

- (void)receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void *)context
{
    unsigned char *incomingPacket = (unsigned char *)[data bytes];
    textField.text = [NSString stringWithCString:(const char *)incomingPacket encoding:NSUTF8StringEncoding];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜