Game Center を使用して認証する

Game Center を使用して、Firebase で構築した Apple プラットフォーム ゲームにプレーヤーをログインさせることができます。Firebase で Game Center のログインを使用するには、まず、ローカル プレーヤーが Game Center にログインしていることを確認し、GameCenterAuthProvider オブジェクトを使用して Firebase 認証情報を生成します。この認証情報を使用して、Firebase で認証を受けることができます。

準備

Swift Package Manager を使用して Firebase の依存関係をインストールし、管理します。

  1. Xcode でアプリのプロジェクトを開いたまま、[File] > [Add Packages] の順に移動します。
  2. プロンプトが表示されたら、Firebase Apple プラットフォーム SDK リポジトリを追加します。
  3.   https://github.com/firebase/firebase-ios-sdk
  4. Firebase Authentication ライブラリを選択します。
  5. 完了すると、Xcode がバックグラウンドで依存関係の解決とダウンロードを自動的に開始します。

次に、以下の構成手順を行います。

  1. Apple アプリを Firebase に登録します。そのためには、登録セクションにアプリのバンドル ID を入力し、加えて App Store ID やチーム ID などのオプション情報も入力します。これは、ログインを完了する前にユーザーの Game Center 認証情報の対象デバイスを安全に確認するために必要です。
  2. Firebase プロジェクトのログイン プロバイダとして、次のように Game Center を有効にします。
    1. Firebase コンソールで [Authentication] セクションを開きます。
    2. [ログイン方法] タブで、Game Center ログイン プロバイダを有効にします。

Game Center のログインをゲームに統合する

まず、ゲームで Game Center をまだ使用していない場合は、Apple のデベロッパー サイトに記載されている Incorporating Game Center into Your GameAuthenticating a Local Player on the Device の手順に沿って操作します。

iTunes Connect に提供したバンドル ID が、アプリを Firebase プロジェクトに接続したときに使用したバンドル ID と一致していることを確認してください。

Game Center の統合の一環として、Game Center 認証プロセスの複数のポイントで呼び出される認証ハンドラを定義します。このハンドラで、プレーヤーが Game Center でログインしているかどうかを確認します。プレーヤーが Game Center でログインしている場合は、引き続き Firebase にログインできます。

Swift

let localPlayer = GKLocalPlayer.localPlayer()
localPlayer.authenticateHandler = { (gcAuthViewController?, error) in
  if let gcAuthViewController = gcAuthViewController {
    // Pause any activities that require user interaction, then present the
    // gcAuthViewController to the player.
  } else if localPlayer.isAuthenticated {
    // Player is signed in to Game Center. Get Firebase credentials from the
    // player's Game Center credentials (see below).
  } else {
    // Error
  }
}

Objective-C

__weak GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
localPlayer.authenticateHandler = ^(UIViewController *gcAuthViewController,
                                    NSError *error) {
  if (gcAuthViewController != nil) {
    // Pause any activities that require user interaction, then present the
    // gcAuthViewController to the player.
  } else if (localPlayer.isAuthenticated) {
    // Player is signed in to Game Center. Get Firebase credentials from the
    // player's Game Center credentials (see below).
  } else {
    // Error
  }
};

Firebase で認証する

ローカル プレーヤーが Game Center を使用してログインしていることを確認した後、GameCenterAuthProvider.getCredential()AuthCredential オブジェクトを作成し、そのオブジェクトを signIn(with:) に渡して、プレーヤーをゲームにログインさせます。

Swift

// Get Firebase credentials from the player's Game Center credentials
GameCenterAuthProvider.getCredential() { (credential, error) in
  if let error = error {
    return
  }
  // The credential can be used to sign in, or re-auth, or link or unlink.
  Auth.auth().signIn(with:credential) { (user, error) in
    if let error = error {
      return
    }
    // Player is signed in!
  }

Objective-C

// Get Firebase credentials from the player's Game Center credentials
[FIRGameCenterAuthProvider getCredentialWithCompletion:^(FIRAuthCredential *credential,
                                                         NSError *error) {
  // The credential can be used to sign in, or re-auth, or link or unlink.
  if (error == nil) {
    [[FIRAuth auth] signInWithCredential:credential
                              completion:^(FIRUser *user, NSError *error) {
      // If error is nil, player is signed in.
    }];
  }
}];

次のステップ

ユーザーが初めてログインすると新しいユーザー アカウントが作成され、ユーザーの Game Center ID にリンクされます。この新しいアカウントは Firebase プロジェクトの一部として保存され、プロジェクト内のすべてのアプリでユーザーを特定するために使用できます。

ゲームでは、User オブジェクトからユーザーの Firebase UID を取得できます。

Swift

let user = Auth.auth().currentUser
if let user = user {
  let playerName = user.displayName

  // The user's ID, unique to the Firebase project.
  // Do NOT use this value to authenticate with your backend server,
  // if you have one. Use getToken(with:) instead.
  let uid = user.uid
}

Objective-C

FIRUser *user = [FIRAuth auth].currentUser;
if (user) {
  NSString *playerName = user.displayName;

  // The user's ID, unique to the Firebase project.
  // Do NOT use this value to authenticate with your backend server,
  // if you have one. Use getTokenWithCompletion:completion: instead.
  NSString *uid = user.uid;
}

Firebase Realtime Database と Cloud Storage のセキュリティ ルールでは、ログイン済みユーザーの一意のユーザー ID を auth 変数から取得し、それを使用して、ユーザーがアクセス可能なデータを制御できます。

ユーザーの Game Center のプレーヤー情報を取得したり、Game Center サービスにアクセスしたりするには、Game Kit で提供されている API を使用します。

Firebase からユーザーをログアウトするには、Auth.signOut() を呼び出します。

Swift

let firebaseAuth = Auth.auth()
do {
  try firebaseAuth.signOut()
} catch let signOutError as NSError {
  print ("Error signing out: %@", signOutError)
}

Objective-C

NSError *signOutError;
BOOL status = [[FIRAuth auth] signOut:&signOutError];
if (!status) {
  NSLog(@"Error signing out: %@", signOutError);
  return;
}