How to send/receive non-ascii string

My game uses Game Center and is required to send and receive "data" between all players in the game.


I convert my game data text string (ie: textStr) into byte data using the code below. I then send the byte data out.


var byteData = Data.init()

byteData = textStr.data(using: .ascii)!


When the byte data is received, I convert the byte data back into a game data text string (ie: receivedStr) using the code below:


let receivedStr = String(data: didReceiveData, encoding: .ascii)!


The game data text string I am sending includes the player's Game Center "displayName" value. It just occurred to me that the Game Center "displayName" value might not be completely made of ascii characters. If this is true, then the code used to convert my game data text string into byte data (see above) will crash since a non-ascii character will be encountered.


Question:

How can I convert a text string, which might include non-ascii characters, into byte data so it can be sent/received successfully?

Answered by OOPer in 410138022

Use `.utf8` instead of `.ascii`. Swift String is based on Unicode and `.utf8` can represent all Unicode characters.

Accepted Answer

Use `.utf8` instead of `.ascii`. Swift String is based on Unicode and `.utf8` can represent all Unicode characters.

thanks a lot! That worked!

How to send/receive non-ascii string
 
 
Q