Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
FirebaseのRealtimeDatabaseをUnityからTwitter認証を用いてデータ取得するSample
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using TwitterKit.Unity;
using Firebase;
using Firebase.Database;
using Firebase.Unity.Editor;
public class PUFirebaseTwitterLogin : MonoBehaviour {
// Twitter
private string _AccessToken;
private string _Secret;
private string _UserName;
// Firebase
private DatabaseReference _FirebaseDB;
private Firebase.Auth.FirebaseUser _FirebaseUser;
void Start () {
Twitter.Init();
this.TwitterAuth();
// Firebase RealtimeDatabase接続初期設定
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("Firebase Realtime Database URL");
// Databaseの参照先設定
_FirebaseDB = FirebaseDatabase.DefaultInstance.GetReference("UnitySample/Ranking");
}
public void FirebaseLogin() {
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
Firebase.Auth.Credential credential = Firebase.Auth.TwitterAuthProvider.GetCredential(_AccessToken, _Secret);
auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
if (task.IsCanceled) {
Debug.LogError("[Info ] : SignInWithCredentialAsync canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("[Error ] : SignInWithCredentialAsync fatal. an error: " + task.Exception);
return;
}
_FirebaseUser = task.Result;
// 認証完了したらデータを読み込む
this.GetRankingData();
});
}
public void TwitterAuth() {
Debug.Log("[Info] : start login");
TwitterSession session = Twitter.Session;
if (session == null) {
Twitter.LogIn(TwitterLoginComplete, TwitterLoginFailure);
} else {
TwitterLoginComplete(session);
}
}
public void TwitterLoginComplete(TwitterSession session) {
Debug.Log("[Info] : Login success. " + session.authToken);
_AccessToken = session.authToken.token;
_Secret = session.authToken.secret;
_UserName = session.userName;
this.FirebaseLogin();
}
public void TwitterLoginFailure(ApiError error) {
Debug.Log("[Error ] : Login faild code =" + error.code + " msg =" + error.message);
}
void GetRankingData() {
// スコアが1番高いものを取得
_FirebaseDB.OrderByChild("score").LimitToLast(1).GetValueAsync().ContinueWith(task => {
if (task.IsFaulted) {
// 取得エラー
Debug.Log("[ERROR] get ranking sort");
} else if (task.IsCompleted) {
// 取得成功
Debug.Log("[INFO] get ranking success.");
DataSnapshot snapshot = task.Result;
IEnumerator<DataSnapshot> result = snapshot.Children.GetEnumerator();
int rank = 0;
string json = snapshot.GetRawJsonValue();
while (result.MoveNext()) {
DataSnapshot data = result.Current;
string name = (string)data.Child("name").Value;
// Firebaseの数値データはLong型となっているので、一度longで受け取った後にintにキャスト
int score = (int)(long)data.Child("score").Value;
Debug.Log("name : " + name + " score : " + score);
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.