Apple Game Center🔗

Apple Game Center - Games on macOS, iOS, watchOS and tvOS can use Game Center, Apple's social gaming network. Game Center allows your users to track their best results in the leaderboard, compare their achievements, invite friends to play the game. Applications may include any or all of the following features supported by Game Center:
- Ratings - compares ratings with player friends and other players from around the world
- Achievements - Points are awarded to players as part of the Game Center Achievement Tracking System. Players can earn points by completing certain in-game tasks. Players cannot use the section for anything else but to evaluate the progress in the games. It was designed so that players can communicate and compete with each other.
MRGSAuthentication makes it easy to integrate this social network into your application.
Initial setup🔗
Before you begin, you need to configure certificates and keys in your Apple Developer account to activate the functionality of the Apple Game Center. Add the Apple Game Center for your application on the Certificates, Identifiers & Profiles page in your developer's account.
Also, in the Xcode project, in the 'Signing & Capabilities' tab, you need to add the Apple Game Center:
In Unity
Add the code to the Unity post build process:
public class PostBuildProcessSample
{
[PostProcessBuild]
public static void PostProcessBuild(BuildTarget target, string path)
{
if (target == BuildTarget.iOS)
{
#if UNITY_IOS
string projPath = PBXProject.GetPBXProjectPath(path);
PBXProject proj = new PBXProject();
proj.ReadFromString(File.ReadAllText(projPath));
#if UNITY_2019_3_OR_NEWER
string projectTarget = proj.GetUnityMainTargetGuid();
#else
string targetName = PBXProject.GetUnityTargetName();
string projectTarget = proj.TargetGuidByName(targetName);
#endif
//Adding capabilities
#if UNITY_2019_3_OR_NEWER
ProjectCapabilityManager projectManager = new ProjectCapabilityManager(projPath, "ios.entitlements", targetGuid: projectTarget);
#else
ProjectCapabilityManager projectManager = new ProjectCapabilityManager(projPath, "ios.entitlements", targetName);
#endif
projectManager.AddGameCenter();
projectManager.WriteToFile();
#endif
}
}
}
Or manually enable it in an already generated project:

Then press the “+” on the “Capability” button and select “Apple Game Center”.
In iOS
In XCode project:

Then press the “+” on the “Capability” button and select “Apple Game Center”.
Add dependencies🔗
Add the MRGS SDK to the project:
Unity:
Adding to the project (general instruction)
Step 1. Add Sources
To add MRGS to a project via the Unity Package Manager (available from Unity 2018+) simply add a scopedRegistries section to the Packages/manifest.json file by adding the following entry:
{
"dependencies": {
...
},
"scopedRegistries": [
{
"name": "MRGS",
"url": "https://mrgs-nexus.my.games/repository/mrgs-uninty-plugins/",
"scopes": [
"games.my.mrgs"
]
}
]
}
Alternatively, you can click Edit -> Project Settings -> Package Manager -> '+' in scoped registry section, and fill in the fields according to the data above.
Step 2. Add dependency
- Click
Window -> Package Manager -> select 'Packages: MyRegistries' from dropdown list, select packageMRGSAuthenticationfrom the list, then click "Install" - Import the module:
using MRGS;
- Download the latest version of the library. Unzip the archive.
- (For unitypackage integration) In Unity, click
Assets -> Import Package -> Custom Package, and select thegames.my.mrgs.authentication.unitypackagepackage from the downloaded archive. - (For tgz integration) In Unity, click
Window -> Package Manager -> '+' -> Add package from tarball, and select thegames.my.mrgs.authentication-<version> package. tgzfrom the downloaded archive. - Import the module:
using MRGS;
iOS:
Adding to the project (general instruction)
Step 1: Add dependencies
Via Package collection
- In Xcode select File > Add Packages
- Select "+" > "Add Swift Package Collection"
- Insert URL:
https://mrgs-nexus.my.games/repository/ios-sdks/MRGSPackageCollection.json - Select module MRGSAuthentication from "MRGS Package Collection".
- Or you can select "MRGS" package from "MRGS Package Collection" (contains all mrgs modules as products) and then select "MRGS/Authentication" product only.
Individual packages
- In Xcode select File > Add Packages
- In the search bar at the top right, paste the URL:
https://mrgs-gitea.my.games/mrgs/mrgsauthentication-ios-sdk.git - Add a module to your project
- Or you can paste the url
https://mrgs-gitea.my.games/mrgs/ios-sdks.gitto include the "MRGS" package which contains all mrgs modules as products and then select only the product" MRGS/Authentication".
Step 2: Add support for ObjectiveC categories
- Set the
-ObjCflag in the "Other linker Flags" field in the project settings. - Import the module in code:
@import MRGServiceKit;or@import MRGSAuthentication;or#import <MRGSAuthentication/MRGSAuthentication.h>
Step 1. Add Sources
In your podfile, add sources to the top of the file:
source 'https://github.com/CocoaPods/Specs.git' # For main repo
source 'https://mrgs-gitea.my.games/mrgs/cocoapods-specs.git' # For MRGS repo
Step 2: Add dependencies
Add the latest version of MRGSAuthentication to target:
To add via subspecs:
To add via individual modules:
To add all mrgs modules:
Step 3: Install dependencies
- Run
pod install(orpod install --repo-updateif necessary) - Import the module in code:
@import MRGServiceKit;or@import MRGSAuthentication;or#import <MRGSAuthentication/MRGSAuthentication.h>
Step 1: Add dependencies
Add the dependency to your Cartfile:
binary "https://mrgs-nexus.my.games/repository/ios-sdks/MRGSAuthentication/MRGSAuthentication.json" ~> 5.0.0
Step 2: Install dependencies
- Run
carthage update --use-xcframeworks - Add downloaded frameworks to your project (make sure "do not embed" option is enabled)
- Set the
-ObjCflag in the "Other linker Flags" field in the project settings. - Import the module in code:
@import MRGServiceKit;or@import MRGSAuthentication;or#import <MRGSAuthentication/MRGSAuthentication.h>
- Download the latest version of the library. Unzip the archive.
-
Add
MRGSAuthentication.xcframeworkfrom the downloaded archive to your project (Drag the libraries to the "Linked frameworks and Libraries" section) (Also contains MRGSAuthentication.framework for compatibility - fat framework) -
Set the
-ObjCflag in the "Other linker Flags" field in the project settings. - Import the module in code:
@import MRGSAuthentication;or#import <MRGSAuthentication/MRGSAuthentication.h> - Also, you can add the
MRGServiceKit.handmodule.modulemapfiles from the archive to your project, or specify the path to them in the project settings in theBuild Settings -> Header search pathssection. Now, instead of importing each of our frameworks separately, you can only import one header file:@import MRGServiceKit;
Setting achievements and ratings🔗
In order for authorization to work correctly, according to this post you must add at least one achievement in your application’s account and one rating table. They can be fictitious, and not be shown anywhere, but for correct operation they are necessary. To add a leaderboard and achievements, read on this page
Important User Identity Information🔗
Initially, the Apple Game Center used a single user ID that does not change in all games. Starting with iOS 12.4, Apple marked the playerId field as deprecated, since they considered such an identifier to be contrary to their user-privecy concept. Instead of this identifier, they added two new ones - teamPlayerId andgamePlayerId.
teamPlayerId- user identifier unique within the application publishergamePlayerId- user identifier unique within a particular application
That is, if you publish several games under one publisher, then the teamPlayerId for the same user in all these games will be the same, andgamePlayerId will be different in each of the games, but if suddenly your game starts to be published from another publisher, then teamPlayerId will change, andgamePlayerId will remain unchanged. In addition, Apple says that sometimes these fields may not be, and they do not specify how to react to this. We will return an authorization error if none of all three identifiers is present.
We don’t know how long the old playerId property will work, but we take it as the basis (for the returned object MRGSAuthenticationUser.userId), if it is not there, then the teamPlayerId field will be used for the user ID. In order to prepare for the transition to a new identifier, in the field MRGSAuthenticationUser.optionalParams we add a dictionary with the corresponding fields -teamPlayerId and gamePlayerId, in which the new identifiers are stored (if there are any, otherwise an empty string is stored).
For more details, see videos from the WWDC 2019 session
Automatic login at restart🔗
Apple Game Center does not save the login state when the application is restarted, that is, after the restart, the system will assume that the user is not logged in. At the same time, when you re-login, the bubble will be displayed at the top of the screen with a user's greeting, without entering a login and password. Therefore, projects usually remember that they logged in at least once, and on the restart they automatically call the login method.

To make it easier for you to integrate the Apple Game Center and not make the automatic login mechanism on each launch, we added the automatic login setting, in which we will perform the above steps by ourselves (In addition, the exit method is not natively provided in this network, therefore, with the usual it doesn’t do anything during configuration, and when auto-login is enabled, the exit method disables auto-login until the next login method call).
In order to enable auto-login, when starting the MRGS SDK, you need to add the appropriate setting in the external SDK parameters:
using MRGS;
public class MasterController : MonoBehaviour
{
void Awake()
{
// Configure MRGS Settings
// ...
var modulesParams = new List<MRGSExternalSDKSettings>
modulesParams.Add(new MRGSAppleGameCenterParams
{
AutomaticallyStartOnLaunch = true
});
// Configure external SDKs and MRGS initialization
// ...
MRGService.Instance.Initialize(serviceParams, sdkParams)
}
}
@import MRGService;
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Configure MRGS Settings
// ...
//Configure external SDKs
MRGSAppleGameCenterParams* appleGameCenterParams = [[MRGSAppleGameCenterParams alloc] init];
appleGameCenterParams.automaticallyStartOnLaunch = true;
NSArray *externalParams = @[ ..., appleGameCenterParams];
[MRGService startWithServiceParams:<params> externalSDKParams:externalParams delegate:nil];
}
Working with the MRGSAuthentication interface🔗
To work with the Apple Game Center, use the MRGSAuthenticationAppleGameCenter class. Please note that this class implements our main protocol MRGSAuthentication, that is, it has all the methods of this protocol. The following describes the standard implementation of the MRGSAuthentication interface:
Delegate🔗
Before you start working with the API, you must install and implement a delegate that accepts callbacks:
// Setting
// 'this' conforms to 'IMRGSAuthenticationDelegate' protocol
MRGSAuthenticationAppleGameCenter.Instance.Delegate = this;
// Implementation
// The method that is called when the user has logged out of the social network remotely, or his session has ended.
public void OnAuthenticationProviderDidLogoutUser(MRGSAuthentication provider, MRGSAuthenticationUser user){
Debug.Log("MRGSAuthentication<Unity> - OnAuthenticationProviderDidLogoutUser: " + user + "\nNetwork: " + provider.SocialId().ToString());
}
// Setting
[MRGSAuthenticationAppleGameCenter sharedInstance].delegate = self;
// Implementation
// The method that is called when the user remotely logs out of the social network, or his session ends.
- (void)authenticationProvider:(id<MRGSAuthentication>)provider didLogoutUser:(MRGSAuthenticationUser *)user{
NSLog(@"User did logout: \n%@", user);
}
// The method that is called when the controller needs to be displayed to authorize the user.
- (void)shouldPresentAuthorizationController:(UIViewController *)viewController {
UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
[rootVC presentViewController:viewController animated:YES completion:nil];
}
Status🔗
Then, you need to check the authorization status (whether the user is logged in):
Login🔗
For regular login, use one of the following methods:
// If error occured, error object will be non-null
MRGSAuthenticationAppleGameCenter.Instance.Login((MRGSError error) => {
if (error == null) {
// Auth success
}
});
// The response will include an object describing the user and the token, and an error object, if any.
MRGSAuthenticationAppleGameCenter.Instance.Login((MRGSAuthenticationCredential credentials, MRGSError error) => {
Debug.Log("MRGSAuthenticationAppleGameCenter:\nCredentials: " + credentials + "\nError:\n" + error);
if (error == null) {
// Auth success
}
});
// Only the object of the error will come in the answer, if it happened
[[MRGSAuthenticationAppleGameCenter sharedInstance] login:^(NSError *error) {
if (!error) {
// Auth success
}
}];
// The response will contain an object describing the user and the token, and the object of the error if it happened
[[MRGSAuthenticationAppleGameCenter sharedInstance] loginWithCompletionHandler:^(MRGSAuthenticationCredential *credentials, NSError *error) {
NSLog(@"Result - %@. Error - %@", credentials, error);
if (!error) {
// Auth success
}
}];
User Verification
If you want to check the user on the server, then you can get the necessary data from the credentials.accessToken.optionalParams field, namely:
Important
The native Apple Game Center interface does not provide the ability to force authorization a second time in a session. That is, if the user canceled the login once during the session, or it was unsuccessful, the window will not be shown again. In such cases, when you call the login method, we will immediately return you an error with the code '-102' in the result. It is best to show the user a window with a call to open the "Game Center" section in the system settings and log into the account there, and then return to the application after receiving such an error.
Authorization Status🔗
To get all the information about the current authorization status and user information, use the methods:
// The information about the user, identifier, name, email, etc.
MRGSAuthenticationAppleGameCenter.Instance.GetCurrentUser((MRGSAuthenticationUser user, MRGSError error) => {
Debug.Log("MRGSAuthenticationAppleGameCenter:\User: " + user + "\nError:\n" + error);
if (error == null) {
// Work with user data
}
});
// Information about the token, lifetime, etc.
MRGSAuthenticationAppleGameCenter.Instance.GetAccessToken((MRGSAuthenticationAccessToken token, MRGSError error) => {
Debug.Log("MRGSAuthenticationAppleGameCenter:\Token: " + token + "\nError:\n" + error);
if (error == null) {
// Work with token info
}
else if (error.Code == (int)MRGSAuthenticationErrorCode.ConnectionFailed)
{
// No network, try later
}
else
{
// Logout user from app (MRGS will logout automatically in SDK)
}
});
// An object is returned that combines information about the user (identifier, name, email, etc.) and about the token.
[[MRGSAuthenticationAppleGameCenter sharedInstance] getCredentials:^(MRGSAuthenticationCredential *credentials, NSError *error) {
NSLog(@"Result - %@. Error - %@", credentials, error);
if(!error){
// Credentials data work
}
}];
// Information about the user - identifier, name, email, etc.
[[MRGSAuthenticationAppleGameCenter sharedInstance] getCurrentUser:^(MRGSAuthenticationUser *user, NSError *error) {
NSLog(@"User - %@. Error - %@", user, error);
if(!error){
// User data work
}
}];
// Information about the token - lifetime, etc.
[[MRGSAuthenticationAppleGameCenter sharedInstance] getAccessToken:^(MRGSAuthenticationAccessToken *token, NSError *error) {
if (!error) {
NSLog(@"getAccessToken result - %@", token);
} else {
NSLog(@"getAccessToken error - %@", error);
}
}];
Logout🔗
In order to "log out" from a user’s account, use the method:
Working with the MRGSAuthenticationGames interface🔗
The protocol for working with gaming social networks is MRGSAuthenticationGames. It allows you to interact with player achievements and player rating tables. The following describes the standard implementation of the MRGSAuthenticationGames interface:
Work with player achievements (Achievements)🔗

To get a list of available achievements, use the method:
If successful, you will receive an array of objects of type MRGSAuthenticationAchievement that describe each achievement, otherwise an error will occur.
To set the progress for the user for a specific achievement, use the method:
The percentage of completion of the achievement and its identifier are passed to the method (can be obtained from previously received objects of the type MRGSAuthenticationAchievement), an error will be returned if it occurred.
To display the progress screen, use the method:
The callback will be called to the event that the user closes the achievement screen.
Working with player rating tables (Leaderboards)🔗

To get a list of available rating tables, use the method:
If successful, you will receive an array of objects of type MRGSAuthenticationLeaderboard that describe each rating table, otherwise an error will occur.
To set points for the user for a specific rating table, use the method:
This method receives points for the current user in the rating table and the identifier of a specific table (can be obtained from previously received objects of the type MRGSAuthenticationLeaderboard), an error will be returned if it occurs.
To display a screen with all rating tables, use the method:
The callback will be called to the event when the user closes the screen with all ratings.
To display a screen with a specific rating table, use the method:
The identifier of the rating table is passed to the method. The callback will be called to the event when the user closes the rating table screen.
To get the current rating for the user, or for all users of this rating, use the appropriate methods:
// For current user
MRGSAuthenticationAppleGameCenter.Instance.GetCurrentPlayerScoreForLeaderboard("some_leaderboard_id", MRGSAuthenticationLeaderboardTimeScope.AllTime, MRGSAuthenticationLeaderboardCollectionType.Public, (MRGSAuthenticationLeaderboardScore score, MRGSError error) => {
if(error == null){
// Operation completed successfully, work with data
}
});
// For all users
MRGSAuthenticationAppleGameCenter.Instance.GetAllPlayersScoresForLeaderboard("some_leaderboard_id", MRGSAuthenticationLeaderboardTimeScope.AllTime, MRGSAuthenticationLeaderboardCollectionType.Public, (List<MRGSAuthenticationLeaderboardScore> scores, MRGSError error) => {
if(error == null){
// Operation completed successfully, work with data
}
});
// For current user
[[MRGSAuthenticationAppleGameCenter sharedInstance] getCurrentPlayerScoreForLeaderboardWithId: @"some_leaderboard_id" timeScope:MRGSAuthenticationLeaderboardTimeScopeAllTime collectionType:MRGSAuthenticationLeaderboardCollectionPublic completionHandler:^(MRGSAuthenticationLeaderboardScore *score, NSError *error) {
if(!error){
// Operation completed successfully, work with data
}
}];
// For all users
[[MRGSAuthenticationAppleGameCenter sharedInstance] getAllPlayersScoresForLeaderboardWithId: @"some_leaderboard_id" timeScope:MRGSAuthenticationLeaderboardTimeScopeAllTime collectionType:MRGSAuthenticationLeaderboardCollectionPublic completionHandler:^(NSArray *scores, NSError *error) {
if(!error){
// Operation completed successfully, work with data
}
}];
The identifier of the rating table, the time for which it is necessary to collect data, the type of data collected (visibility for all, or only for friends) is passed to the method. An object, or an array of objects of type MRGSAuthenticationLeaderboardScore, describing the user rating points, will come in response.
Additional features of Apple Game Center🔗
Also, MRGSAuthenticationAppleGameCenter offers you several additional features exclusively for working with the Apple Game Center:
In order to get an avatar for a user with a given identifier, use the method:
In order to reset all achievements of the current user, use the method:
In order to get a list of all friends of the current user, use the method:
In order to get an object with a user description for a given identifier, use the method:
In order to get objects with a description of users with the given identifiers, use the method:
Created: 2020-05-28