Push - SrejonKhan/FirebaseRestClient GitHub Wiki
Overview
Push functionality in this library is a bit different from the actual Firebase SDK. In this library, when Push()
function called, it implicitly completes the followings task -
- Generate a Push ID locally
- Write passed body to the following path (childs + push id)
- Returns generated Push ID as string
Example
If you want to push a object
directly -
var userObject = new User("DefaultName");
firebase.Child("users").Push(userObject).OnSuccess(uid =>
{
//Returns Push ID in string
Debug.Log(uid);
});
If you want to push with JSON String
-
string jsonString = JsonUtility.ToJson(userObject);
firebase.Child("users").Push(jsonString).OnSuccess(uid =>
{
//Returns Push ID in string
Debug.Log(uid);
});
If you just want a Push ID, not directly writing -
string pushId = firebase.GeneratePushID();
Use Case
Push()
method generates a unique key every time a new child is added to the specified Firebase reference. There is no write conflict chance even several clients can add children to the same location at the same time. "The unique key generated by Push()
is based on a timestamp, so list items are automatically ordered chronologically."
Let's imagine you would like to add user information to the database whenever a user registers. Now we have a class called User
which has all information we will upload -
[System.Serializable]
public class User
{
public int id;
public string username;
public string likes;
public string hates;
public User() { }
public User(int id, string username, string likes, string hates)
{ //assigning codes... }
}
We have two different way to upload user data to database. The first way is directly to upload the user
object or convert it to JSON string to upload.
var userObject = new User(123, "DefaultName", "Pizza", "Black Pudding"); //user object
//Push to `users/$UID` reference, $UID is unique key.
firebase.Child("users").Push(userObject).OnSuccess(uid =>
{
//Returns Push ID in string
Debug.Log(uid);
});
//Push with JSON String
string jsonString = JsonUtility.ToJson(userObject); //json string
firebase.Child("users").Push(jsonString).OnSuccess(uid =>
{
//Returns Push ID in string
Debug.Log(uid);
});