Retrieving the Local Player’s Friends Information

Problem

You’ve added friends to the local player’s Game Center account, but now you want to enumerate them and retrieve their information, such as their alias.

Solution

Use the friends property of the local player’s object, an instance of GKLocalPlayer.

Discussion

The GKLocalPlayer class has a property called friends of type NSArray. This property will contain the players that the local player is friends with. The array represents the players using their player IDs (explained in Retrieving the Local Player’s Information).

I said will in the previous paragraph because, after authentication of the local player, this array is empty (nil). You need to call the loadFriendsWithCompletionHandler: instance method of the GKLocalPlayer class to load the player ID for each of the local player’s friends. After retrieving the IDs, call another method to retrieve other information for each friend based on his or her player ID.

The loadFriendsWithCompletionHandler: instance method of the GKLocalPlayer class accepts one parameter, which should be a block that returns void (or in other words, doesn’t return anything). This block object will have two parameters. The first is of type NSArray and will, upon return, contain the friend IDs of the local player. The second is of type NSError and will indicate whether an error occurred during the process.

Note

To avoid repeating code over and over, I assume that you have already authenticated the local player using ...

Get Writing Game Center Apps in iOS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.