我正在尝试通过 iPhone 中的 Peer to Peer Networking 发送一些文本。我稍微修改了 GKTank Sample 以使其发送字符串而不是自定义结构数据。以下是我编写的代码。我的问题是我可以将@"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];
}
}