我怎么知道Firebase是否是首次登录?数据存在吗?

时间:2019-01-25 07:53:04

标签: firebase firebase-realtime-database firebase-authentication unityscript

这是Firebase匿名登录代码。

我想知道如何编码if(????)

当我读取数据时,我认为如果没有数据,它将为null。

DBreference.Child("UserData").Child(fireUser .UserId).GetValueAsync()

此代码不为空

auth = FirebaseAuth.DefaultInstance;
DBreference = FirebaseDatabase.DefaultInstance.RootReference;
User userData = null; // User class include userdata

auth.SignInAnonymouslyAsync().ContinueWith(task =>
{
 fireUser = task.Result;
 //Always automatically login success

 //This part is read Data from Firebase.Database
 DBreference.Child("UserData").Child(fireUser.UserId).
 GetValueAsync().ContinueWith(task2 => 
 {
     if(????) // data dosen't exist
     {
         userData = new User();
         string jsonString = JsonFx.Json.JsonWriter.Serialize(userData);
         DBreference.Child("UserData").Child(fireUser.UserId).
         SetRawJsonValueAsync(jsonString);
     }
     else // data exists
     { 
         jsonString = task2.Result.GetRawJsonValue();
         userData = JsonFx.Json.JsonReader.Deserialize<User>(jsonString);            
     }
 });
});

1 个答案:

答案 0 :(得分:0)

好吧,在阅读您的评论后,我现在明白了 您需要交换if / else

auth = FirebaseAuth.DefaultInstance;
DBreference = FirebaseDatabase.DefaultInstance.RootReference;

auth.SignInAnonymouslyAsync().ContinueWith(task =>
{
 fireUser = task.Result;

 if(task.IsFaulted) // user doesn't exist
 { 
   userData = new User(); 
   string jsonString = JsonFx.Json.JsonWriter.Serialize(userData);
   DBreference.Child("UserData").Child(fireUser .UserId).           
   SetRawJsonValueAsync(jsonString);
 }
 else //user exists
 {
    DBreference.Child("UserData").Child(fireUser .UserId).
    GetValueAsync().ContinueWith(task3 =>
    {
        jsonString = task3.Result.GetRawJsonValue();      
        userData = JsonFx.Json.JsonReader.Deserialize<User>(jsonString);
    });
 }
});