Is it possible to send text chat msgs to other players via Game Center? is their any dedicated way to do that with the GameKit API? or would it just have to be put into the turn data that is sent between players?
3 Answers
You can just send the text as normal data during the game. In order to do that
Method to prepare data to send
-(void)sendText:(NSString *) text {
NSString * text2Send = [NSString stringWithFormat:@"%@", text];
[self sendData:[text2Send dataUsingEncoding:NSUTF8StringEncoding]];
}
The send data method will be the normal data sending method of Game center as
- (BOOL)sendDataToAllPlayers:(NSData *)data withDataMode:(GKMatchSendDataMode)mode error:(NSError **)error;
and in order to resolve the received data
NSString * rawText = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
if(rawText.length > 0)
{
//Do what ever you want with the text
}
Like already proposed, you can use GKTurnBasedMatch's matchData for that. If your game is turn-based, you can have two game data message types: one for sending game data at the end of each player's turn, and the other for sending chat messages. Or you can combine them so that a message is sent when each player ends her turn. However if you only use matchData to send chat messages, make sure it doesn't end player's turn, otherwise you will have game synchronization issues. For that use saveCurrentTurnWithMatchData:completionHandler: method for sending your message; on the other side GameKit will call your turn callback as it receives the message - you should read the updated matchData and see whether it is a message or a game state update - that's relatively easy if you use JSON or XML or NSDictionary serialization for sending data back and forth - you can introduce something like dataType property there that would let you distinguish between text message and game state update.
There's also an option for changing the match.message contents, however if you put your short message there, the opponent(s) will only see it when they receive 'your turn' notification from the GameCenter.