Uwierzytelnij przez Game Center

Za pomocą Game Center możesz logować graczy w grze na platformy Apple opartej na Firebase. Aby używać logowania w Game Center w Firebase, najpierw upewnij się, że lokalny gracz jest zalogowany w Game Center, a następnie użyj obiektu GameCenterAuthProvider, aby wygenerować dane logowania Firebase, których możesz użyć do uwierzytelnienia w Firebase.

Zanim zaczniesz

Do instalacji zależności Firebase i do zarządzania nimi możesz używać menedżera pakietów Swift.

  1. Po otwarciu projektu aplikacji wybierz w Xcode opcję File > Add Packages (Plik > Dodaj pakiety).
  2. Gdy pojawi się prośba, dodaj repozytorium pakietu SDK Firebase na platformy Apple:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. Wybierz bibliotekę Firebase Authentication.
  5. Dodaj flagę -ObjC do sekcji Other Linker Flags (Inne flagi linkera) w ustawieniach kompilacji elementu docelowego.
  6. Gdy skończysz, Xcode zacznie automatycznie wyszukiwać i pobierać zależności w tle.

Następnie wykonaj kilka czynności konfiguracyjnych:

  1. Zarejestruj aplikację Apple w Firebase. Oznacza to wpisanie identyfikatora pakietu aplikacji w sekcji rejestracji wraz z dodatkowymi informacjami opcjonalnymi, takimi jak identyfikator App Store czy identyfikator zespołu. Będzie to wymagane do bezpiecznego zweryfikowania odbiorców danych logowania użytkownika do Game Center przed zakończeniem logowania.
  2. Włącz Game Center jako dostawcę logowania w projekcie Firebase:
    1. W Firebasekonsoli otwórz sekcję Uwierzytelnianie.
    2. Na karcie Metoda logowania włącz dostawcę logowania Game Center.

Integrowanie logowania przez Game Center z grą

Jeśli Twoja gra nie korzysta jeszcze z Game Center, postępuj zgodnie z instrukcjami w sekcjach Incorporating Game Center into Your Game (Włączanie Game Center w grze) i Authenticating a Local Player on the Device (Uwierzytelnianie lokalnego gracza na urządzeniu) na stronie dla deweloperów Apple.

Upewnij się, że identyfikator pakietu podany w iTunes Connect jest zgodny z identyfikatorem pakietu używanym podczas łączenia aplikacji z projektem Firebase.

W ramach integracji z Game Center definiujesz procedurę obsługi uwierzytelniania, która jest wywoływana w wielu punktach procesu uwierzytelniania w Game Center. W tym module obsługi sprawdź, czy gracz jest zalogowany w Game Center. Jeśli tak, możesz kontynuować logowanie się w 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
  }
};

Uwierzytelnianie za pomocą Firebase

Po sprawdzeniu, czy lokalny gracz zalogował się w Game Center, zaloguj go w grze, tworząc obiekt AuthCredentialGameCenterAuthProvider.getCredential() i przekazując go do 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.
    }];
  }
}];

Dalsze kroki

Gdy użytkownik zaloguje się po raz pierwszy, zostanie utworzone nowe konto użytkownika i połączone z jego identyfikatorem Game Center. Nowe konto jest przechowywane w projekcie Firebase i może służyć do identyfikowania użytkownika we wszystkich aplikacjach w projekcie.

W grze możesz uzyskać identyfikator UID Firebase użytkownika z obiektu User:

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;
}

W regułach zabezpieczeń Bazy danych czasu rzeczywistego Firebase i Cloud Storage możesz uzyskać niepowtarzalny identyfikator użytkownika, który jest zalogowany, ze zmiennej auth i użyć go do kontrolowania, do jakich danych użytkownik ma dostęp.

Aby uzyskać informacje o graczu w Game Center lub dostęp do usług Game Center, użyj interfejsów API udostępnianych przez Game Kit.

Aby wylogować użytkownika z Firebase, wywołaj funkcję 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;
}