プログラミング学習日記

プログラミング学習時のメモ帳。

Unity firebase 匿名認証

間違っている場所あったら優しく教えてね

Unityでfirebaseを使う

匿名認証機能を使う.

TwitterGoogleなどの外部アカウントを使って認証することもできるが匿名認証を使うことができる.一度ログインすると,keystore(端末ごとに保持するログイン情報)として保存されるため,その後は認証なしでログイン情報を参照できる.

初期準備

// 初めにインスタンスを取得しておく
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;

匿名Userを作成する

auth.SignInAnonymouslyAsync().ContinueWith(task => {
  if (task.IsCanceled) {
    Debug.LogError("SignInAnonymouslyAsync was canceled.");
    return;
  }
  if (task.IsFaulted) {
    Debug.LogError("SignInAnonymouslyAsync encountered an error: " + task.Exception);
    return;
  }

  Firebase.Auth.FirebaseUser newUser = task.Result;
  Debug.LogFormat("User signed in successfully: {0} ({1})",
      newUser.DisplayName, newUser.UserId);
});

ログイン情報を取得する.

以下のようにuserの情報を取得することができる.

// CurentUserでkeystoreからの情報を用いて取得できる.
Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  string name = user.DisplayName;
  string email = user.Email;
  System.Uri photo_url = user.PhotoUrl;
  string uid = user.UserId;
}

プロフィールの更新をする.

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  Firebase.Auth.UserProfile profile = new Firebase.Auth.UserProfile {
    DisplayName = "Name",
    PhotoUrl = new System.Uri("https://hoge/po/profile.jpg"),
  };
  user.UpdateUserProfileAsync(profile).ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("UpdateUserProfileAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("UpdateUserProfileAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("User profile updated successfully.");
  });
}

参考

Authenticate with Firebase Anonymously using Unity

ブログを見ていただきありがとうございました