在代码中使用Game Center Learderboard的操作

Reporting Scores to Game Center

Your application transmits scores to Game Center by creating a GKScore object. A score object has properties for the player that earned the score, the date and time the score was earned, the category for the leaderboard the score should be reported to, and the score that was earned. Your application configures the score object and then calls its reportScoreWithCompletionHandler:method to send the data to Game Center.

Listing 3-1 shows how to use a score object to report a score to Game Center.

Listing 3-1  Reporting a score to Game Center

- (void) reportScore: (int64_t) score forCategory: (NSString*) category
{
    GKScore *scoreReporter = [[[GKScore alloc] initWithCategory:category] autorelease];
    scoreReporter.value = score;
 
    [scoreReporter reportScoreWithCompletionHandler:^(NSError *error) {
       if (error != nil)
       {
            // handle the reporting error
        }
    }];
}

The score object is initialized with the category identifier for the leaderboard it should be reported to, then the method sets the value property to the score the player earned. The category identifier must be one of the category identifiers you defined when you configured your leaderboards in iTunes Connect. This code for reporting a score does not set the player who earned the score or the time the score was earned; those properties are set automatically when the score object was created. Scores are always reported for the local player.

Recovering from Score-Reporting Errors

If your application receives a network error, you should not discard the score. Instead, store the score object and attempt to report the player’s process at a later time. GKScore objects support the NSCoding protocol, so if necessary, they can be archived when your application terminates and unarchived after it launches.

Showing the Standard Leaderboard

In addition to sending scores to Game Center, your should also allow players to view their scores from within your app. The simplest way to do this is with a GKLeaderboardViewController object. A leaderboard view controller provides a user interface similar to the leaderboard found in the Game Center application. The leaderboard view controller is presented modally by a view controller that you implement in your application.

Listing 3-2 provides a method your view controller can use to display the default leaderboard. The method instantiates a new leaderboard view controller and sets its leaderboardDelegate property to point to your view controller. The view controller then presents the leaderboard and waits for the delegate to be called.

Listing 3-2  Displaying the default leaderboard

- (void) showLeaderboard
{
    GKLeaderboardViewController *leaderboardController = [[GKLeaderboardViewController alloc] init];
    if (leaderboardController != nil)
    {
        leaderboardController.leaderboardDelegate = self;
        [self presentModalViewController: leaderboardController animated: YES];
    }
}

You can configure the leaderboard view controller’s category and timeScope properties before presenting the leaderboard:

  • The category property allows you to configure which category screen is displayed when the leaderboard opens. If you do not set this property, the leaderboard opens to the default category you configured in iTunes Connect.

  • The timeScope property allows you to configure which scores are displayed to the user. For example, a time scope ofGKLeaderboardTimeScopeAllTime retrieves the best scores regardless of when they were scored. The default value isGKLeaderboardTimeScopeToday, which shows scores earned in the last 24 hours.

When the user dismisses the leaderboard, the delegate’s leaderboardViewControllerDidFinish: method is called. Listing 3-3 shows how your view controller should dismiss the leaderboard.

Listing 3-3  Responding when the player dismisses the leaderboard

- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
    [self dismissModalViewControllerAnimated:YES];
}

You may want to save the leaderboard view controller’s category and timeScope properties before disposing of the leaderboard view controller. These properties hold the values of the last selections the player chose while viewing the leaderboards. You can then use those same values to initialize the leaderboard view controller the next time the player wants to see the leaderboard.

Retrieving Leaderboard Scores

If you want your application to examine the score data or create a custom leaderboard view, you can have your application directly load score data from Game Center. To retrieve score data, your application uses the GKLeaderboard class. A GKLeaderboardobject represents a query for data stored on Game Center for your application. To load score data, your application creates aGKLeaderboard object and sets its properties to filter for a specific set of scores. Your application calls the leaderboard object’sloadScoresWithCompletionHandler: method to load the scores. When the data is loaded from Game Center, Game Kit calls the block you provided.

Listing 3-4 shows a typical leaderboard data query. The method for this query initializes a new leaderboard object and configures theplayerScopetimeScope, and range properties to grab the top ten scores earned by anyone playing your game, regardless of when the scores were reported.

Listing 3-4  Retrieving the top ten scores

- (void) retrieveTopTenScores
{
    GKLeaderboard *leaderboardRequest = [[GKLeaderboard alloc] init];
    if (leaderboardRequest != nil)
    {
        leaderboardRequest.playerScope = GKLeaderboardPlayerScopeGlobal;
        leaderboardRequest.timeScope = GKLeaderboardTimeScopeAllTime;
        leaderboardRequest.range = NSMakeRange(1,10);
        [leaderboardRequest loadScoresWithCompletionHandler: ^(NSArray *scores, NSError *error) {
            if (error != nil)
            {
                // handle the error.
            }
            if (scores != nil)
            {
                // process the score information.
            }
            }];
    }
}

Your application can create a leaderboard request that explicitly provides the identifiers for the players whose scores you are interested in. When you provide a list of players, the playerScope property is ignored. Listing 3-5 shows how to use the player identifiers in a list associated with a match in order to load the players’ best scores.

Listing 3-5  Retrieving the top scores for players in a match

- (void) receiveMatchBestScores: (GKMatch*) match
{
    GKLeaderboard *query = [[GKLeaderboard alloc] initWithPlayerIDs: match.playerIDs];
    if (query != nil)
    {
        [query loadScoresWithCompletionHandler: ^(NSArray *scores, NSError *error) {
            if (error != nil)
            {
                // handle the error.
            }
            if (scores != nil)
            {
                // process the score information.
            }
        }];
    }
}

In either case, the returned GKScore objects provide the data your application needs to create a custom view. Your application can use the score object’s playerID to load the player’s alias, as described in “Retrieving Details for Game Center Players.” Thevalue property holds the actual value you reported to Game Center. More importantly, the formattedValue property provides a string with the that actual value formatted according to the parameters you provided in iTunes Connect.

Important You may be tempted to write your own formatting code rather than using the formattedValue property. Do not do this. Using the built-in support makes it easy to localize the score value into other languages, and provides a string that is consistent with the presentation of your scores in the Game Center application.

To maintain an optimal user experience, your app should only query the leaderboard for data it needs to use or display. For example, do not attempt to retrieve all the scores stored in the leaderboard at once. Instead, grab smaller portions of the leaderboard and update your views as necessary.

Retrieving Category Titles

If your application presents a custom leaderboard screen, your application also needs the localized titles of the categories you configured in iTunes Connect. Listing 3-6 shows how your application can load the titles from Game Center. As with most other classes that access Game Center, this code returns the results to your application by calling the block object you provided.

Listing 3-6  Retrieving category titles

- (void) loadCategoryTitles
{
    [GKLeaderboard loadCategoriesWithCompletionHandler:^(NSArray *categories, NSArray *titles, NSError *error) {
        if (error != nil)
        {
            // handle the error
        }
        // use the category and title information
     }];
}

The data returned in the two arrays in Listing 3-6 are the category identifiers and their corresponding titles.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值