3. Gửi dữ liệu

  • Sử dụng SetAsync: để gửi dữ liệu lên FireStore Database

Code mẫu:

Tạo class: FireStoreData

[Serializable]
public class FireStoreData
{
    public string name;
}

Code:



void Start()
{
    StartCoroutine(SendToFireStore("Main", firebaseUser.UserId, new FireStoreData() { name="tuyennv"}));
}
private IEnumerator SendToFireStore(string collectionName, string documentId, FireStoreData data)
{
    FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
    string dataJson=JsonUtility.ToJson(data);
    db.Collection(collectionName).Document(documentId).SetAsync(new Dictionary<string, object>()
                {
                    { "data", dataJson }
                });
    yield return 1;
}

Trong đó:

  • collectionName: là tên collection để lưu trữ các dữ liệu cùng 1 cấu trúc

  • documentId: là các bản ghi lưu trữ dữ liệu (Thường là các userId của firebaseAuth) Xem code lấy firebaseUser

  • data: là dữ liệu được lưu tương ứng với mỗi documentId

Code mẫu lấy firebaseUser

firebaseAuth.SignInWithCredentialAsync(credential).ContinueWithOnMainThread(task =>
            {
                if (task.IsCanceled)
                {
                    return;
                }
                if (task.IsFaulted)
                {
                    return;
                }
                firebaseUser = task.Result;
            });

Kết quả:

Last updated