I'm creating a game that uses GameCenter and I'm trying to send and retrieve data.
This is how I'm sending data: (the function 'sendData' is provided by GameCenter with GameKit)
let nick = GCHelper()
let data = NSData(contentsOfFile: "")
try! nick.match.sendData(toAllPlayers: data as! Data, with: .reliable)
'GCHelper' is a class I'm using that contains many functions for Game Center, a download is further through the questions if you're interested. I just needed to call it to access the function.
Then to retrieve data I'm attempting to use this:
nick.match(GKMatch, didReceive: Data, fromPlayer: String)
Note: I have not filled in any of the above parameters
Here is the function I'm using to retrieve the data:
public func match(_ theMatch: GKMatch, didReceive data: Data, fromPlayer playerID: String) {
if match != theMatch {
return
}
delegate?.match(theMatch, didReceiveData: data, fromPlayer: playerID)
}
The function I'm using 'match()' is apart of the GCHelper class. GCHelper allows for you to create GameCenter game easier. Here is a link in case you want to reference it: https://github.com/jackcook/GCHelper
QUESTION Now that I've showed you all the methods, how would I use the previous method to retrieve data? One of its parameters is 'fromPlayer' and asks for the playerId(String), but how would I know what the other players playerID is? Better yet, how would I retrieve it?
If you don't think this is a good way to handle retrieving data, how could I do it better? Is there another way to do this?
Key Facts: The game requires 2 people and data is being exchanged between these 2 people only. I need to know how to send and retrieve data amongst the 2. Thanks for the help! If you have any questions let me know.
This is the function I'm using to retrieve the data:
open func match(_ theMatch: GKMatch, didReceive data: Data, fromPlayer playerID: String) {
}
Now, the data I'm sending is a string. So I create a variable that unarchives the data and sets it to string format.
let myString = NSKeyedUnarchiver.unarchiveObject(with: data) as! String
After this, I need a way to get that string from the view controller or game center file to my game scene. In which I simply just stored the data using UserDefaults.
let user = UserDefaults.standard
user.set(myString, forKey: "myString")
Then in my SKScene I created a timer, in which it checks every couple of seconds to see if there's a change. It stores the values so that when a new values arrives it can compare and if it is different it does something with it, for example: update player points.
Note: This is what I found to work, someone else may have a better way, but it works fine for me.