LoginSignup
46

More than 5 years have passed since last update.

【ios7版】GameCenterのランキング表示、スコア送信を実装する

Posted at

ios7からGameCenterの実装方法が少々変わったようで、ブログなどに書いているGameCenterの実装方法を試してみても、
ios7では非推奨の警告が出る部分が多かったので、コードを書き直してみました。

リーダーボードの設定などはiTunes connectであらかじめ済ませておいてください。
参考:【iPhoneアプリ】アプリをGame Center対応にする方法(前編: iTunes Connectでの設定編) - 夏までにiPhone アプリつくってみっか!

準備

1,Gamekitフレームワークをプロジェクトに追加
2,Gamekitフレームワークを.hファイルでimport
3,GKGameCenterControllerDelegateを実装


#import <GameKit/GameKit.h>

@interface HogeViewController : UIViewController<GKGameCenterControllerDelegate>

ログイン認証

ログインしているかどうかの確認をするauthenticateLocalPlayerを作成して、ViewDidLoadとかviewWillAppearとかAppDelegateなどで読み込ませる。

/**
 * GameCenterにログインしているか確認処理
 * ログインしていなければログイン画面を表示
 */
- (void)authenticateLocalPlayer
{
    GKLocalPlayer* player = [GKLocalPlayer localPlayer];
    player.authenticateHandler = ^(UIViewController* ui, NSError* error )
    {
        if( nil != ui )
        {
            [self presentViewController:ui animated:YES completion:nil];
        }

    };
}


/**
 * 画面を読み込む際の処理
 */
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self authenticateLocalPlayer];
}

スコア送信

if文でGameCenterにログインしているかどうか確認してログインしていればスコアを送信する。
書き換える部分は:MY_LEADERBOARD_ID, HIGH_SCOREの2点。
エラーの場合はエラーの旨のAlertを表示させると良い感じだと思います。

※スコアで少数の値を送信する場合は値の渡し方に少し注意する必要があるので下記の記事をどうぞ。
参考:Game CenterのLeaderboardで小数(float型)のスコアを送信する - タブレット上のcron

少数値のまま送信するのではなく、*10,*100して整数値に直して送信しないといけないみたいですね。

if ([GKLocalPlayer localPlayer].isAuthenticated) {
            GKScore* score = [[GKScore alloc] initWithLeaderboardIdentifier:MY_LEADERBOARD_ID];
            score.value = HIGH_SCORE;
            [GKScore reportScores:@[score] withCompletionHandler:^(NSError *error) {
                if (error) {
                    // エラーの場合
                }
            }];
        }

リーダーボード表示

Storyboard上でボタン作成して、showRankingと紐づけておけば、
下記コードをコピペでOKだと思います。

/**
 * ランキングボタンタップ時の処理
 * リーダーボードを表示
 */
- (IBAction)showRanking:(id)sender {
    GKGameCenterViewController *gcView = [GKGameCenterViewController new];
    if (gcView != nil)
    {
        gcView.gameCenterDelegate = self;
        gcView.viewState = GKGameCenterViewControllerStateLeaderboards;
        [self presentViewController:gcView animated:YES completion:nil];
    }
}

/**
 * リーダーボードで完了タップ時の処理
 * 前の画面に戻る
 */
- (void)gameCenterViewControllerDidFinish:(GKGameCenterViewController *)gameCenterViewController
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46