adsigel adsigel -4 years ago 180
iOS Question

Instance member 'playerID' cannot be used on type 'GKPlayer'

I'm beginning to implement Game Center in my iOS app, and I would like to use the player ID as my unique identifier elsewhere in the app. However, when I try to declare a variable:

var playerID: String? { GKPlayer.playerID }

I get the error
Instance member 'playerID' cannot be used on type 'GKPlayer'.
Looking through Game Center docs I didn't find anything that could help me (but could easily be me, not the docs). Is there some code I need to execute before declaring playerID? This is all being done after I authenticate the local player, fwiw.

Do I need to use
to get the ID of a single, local user?

Answer Source

You need to get the player objects first, then you can look up the playerID for each. loadPlayers isn't going to help because you have to already know the playerIDs you want when you call loadPlayers.

There are two places you can get the player objects. First, there's the "local player" that's logged into Game Center on the device. Second, both real-time and turn-based matches contain a list of all players participating in that match at that instant.

I don't know swift syntax, but in obj-c, getting the local player's ID looks like:

GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
NSString *playerID = localPlayer.playerID

The match object will have the array of objects for the entire set of players in that match. In a realtime, GKMatch object, the property is called players. In a turn-based GKTurnBasedMatch object, the property is called participants. Getting the list of participants in a turn-based match, for example, looks like:

for (GKTurnBasedMatchParticipant *participant in match.participants)
     GKPlayer *player = participant.player;
     NSString *playerID = player.playerID;

Note that in turn-based matches, when you create a match for, say, 6 players, the creator (the local player) takes the first slot. Participants 2-6 will be empty until those players actually join the game (on their first turn).

Once you have the playerID, you can use it as an identifier in the rest of your code. Later, if you want to look up details about a player, you can call loadPlayers using the playerID you want to look up.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download