Search code examples
iosnsdatagksession

How to pack multiple informations to NSData and Send/Receive/Process the data?


I'm making a small card game on iOS. I'm using GameKit/GKsession to handle my network data transfer.

My question is how to "pack" multiple informations to a NSData and send it. And when the server receive the NSData, how to unpack it and process the information in right way.

For example, I can send and receive the NSString with no problem. But my game has different data type need to send and receive such as UIImage/NSString/NSArray/...

I found the sample project GKTank in SDK. But it's really hard to understand for me. In my guess, it has defined several data types.

Can someone tell me how to let the server know what kind of data the client is sending(NSString?UIImage?) in this method:

- (void)receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void *)context

Solution

  • You are actually looking for two things.

    1) a protocol that bother the sender and receiver understands;

    2) a way to "Serialize" your objects to the data type that feeds to the protocol and "Deserialize" the data for objects.

    For 1, you have various choices such as JSON, XML (string based) and bytes based protocol such as Protocol Buffer.

    For 2, you have various parsers such as SBJson, TBXML and protobuf that helps you to encode and decode the protocol you choose in (1).