I have successfully used the Apple Documentation to connect two players via Game Center and start the game. However, I have been struggling for days at getting the app to send data between two players.
I just need to send an integer between the two players but can't even get the documentation code to run, even after creating the structs etc. Examples I have looked at already are dated or I can't get them to build.
func sendPosition() {
let messageToSend = 123
//what do I need to do messageToSend to send it?
do {
try match.sendData(toAllPlayers: packet, with: .unreliable)
} catch {
}
if error != nil {
// Handle the error.
}
}
func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer) {
//What do I need to do to receive the data?
}
If anyone can help with some working code I can experiment with in Swift 5+ I would be grateful.
After some reading and playing my original code seemed to work!!! If it helps anyone else:
To send:
@IBAction func sendDataBtn(_ sender: Any) {
print("sending data")
let dataString = "Hello, World!"
let dataToSend = dataString.data(using: .utf8)
do {
try myMatch.sendData(toAllPlayers: dataToSend!, with: .reliable)
} catch {
print(error.localizedDescription)
}
}
To receive:
func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer) {
print("Data Received")
let receivedData = String(data: data, encoding: .utf8)
messageLbl.text = receivedData
}