Uwierzytelnij przez Game Center

Za pomocą Game Center możesz logować graczy w grach na platformy Apple utworzonych w Firebase. Aby używać logowania przez 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 celu.
  6. Gdy skończysz, Xcode zacznie automatycznie wyszukiwać i pobierać Twoje zależności w tle.

Następnie wykonaj kilka czynności konfiguracyjnych:

  1. Zarejestruj aplikację Apple w Firebase. Oznacza to, że w sekcji rejestracji musisz wpisać identyfikator pakietu aplikacji oraz dodatkowe informacje opcjonalne, takie jak identyfikator w App Store i identyfikator zespołu. Będzie to wymagane do bezpiecznego zweryfikowania odbiorców danych logowania Game Center użytkownika przed zakończeniem logowania.
  2. Włącz Game Center jako dostawcę logowania w projekcie w Firebase:
    1. W konsoli Firebaseotwórz sekcję Authentication (Uwierzytelnianie).
    2. Na karcie Sign in method (Metoda logowania) włącz dostawcę logowania Game Center.

Zintegruj logowanie 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 (Dołączanie Game Center do gry) 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 przez Ciebie w iTunes Connect jest taki sam jak identyfikator pakietu użyty przy łączeniu aplikacji z projektem w Firebase.

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

Uwierzytelnij w Firebase

Gdy stwierdzisz, że lokalny gracz zalogował się w Game Center, zaloguj go w grze, tworząc obiekt AuthCredential za pomocą GameCenterAuthProvider.getCredential() i przekazując ten obiekt 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. To nowe konto jest przechowywane w projekcie w Firebase i może służyć do identyfikowania użytkownika w każdej aplikacji 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 bezpieczeństwa Bazy danych czasu rzeczywistego Firebase i Cloud Storage możesz uzyskać unikalny identyfikator zalogowanego użytkownika z 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 uzyskać 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 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;
}