我正在尝试通过Peer向iPhone中的Peer Networking发送一些文本。我稍微修改了GKTank Sample,使其发送字符串而不是自定义的struct数据。以下是我写的代码。我的问题是我可以将@“hello”发送到另一个ios设备并且它可以接收数据(长度为5),但它收到的NSData不能转换为NSString,因此接收的数据不能显示为字符串。关于代码有什么问题的任何想法?
- (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];
}
}
答案 0 :(得分:0)
通过将类型转换NSData *解析为char *并使用-stringWithCString:encoding:
从CString获取NSString来解决此问题。
- (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];
}