Type Method

report(_:withCompletionHandler:)

Reports a list of scores to Game Center

Declaration

class func report(_ scores: [GKScore], withCompletionHandler completionHandler: ((Error?) -> Void)? = nil)

Parameters

scores

An array of GKScore objects that contains the scores to report to Game Center.

completionHandler

A block to be called after the score is reported.

The block receives the following parameter:

error

If an error occurred, this parameter holds an error object that describes the problem. If the score was successfully reported, this parameter’s value is nil.

Discussion

Use this class method whenever you need to submit scores to Game Center, whether you are reporting a single score or multiple scores. The method runs through the array of GKScore objects, submitting scores one at a time.

report(_:withCompletionHandler:) provides a sample method to report a score. The GKScore object is initialized with the leaderboard ID for the leaderboard it reports its score to and then the value and context for the score are assigned. The leaderboard ID must be the identifier for a leaderboard you configured in App Store Connect. Scores are always reported for the current local player and never for friends.

Listing 1

Reporting a score to Game Center

- (void) reportScore: (int64_t) score forLeaderboardID: (NSString*) identifier
{
    GKScore *scoreReporter = [[GKScore alloc] initWithLeaderboardIdentifier: identifier];
    scoreReporter.value = score;
    scoreReporter.context = 0;
 
    NSArray *scores = @[scoreReporter];
    [GKScore reportScores:scores withCompletionHandler:^(NSError *error) {
    //Do something interesting here.
    }];
}

When this method is called, it creates a new background task to handle the request. The method then returns control to your game. Later, when the task is complete, GameKit calls your completion handler. The completion handler is always called on the main thread.

See Also