我已經成功安裝了 Firebase 并使用 UID 連接了登錄和注冊。如果用戶在應用程式中保存其他資料,我現在想將其分配給登錄的相應用戶,最好的方法是什么?抱歉,我是 Swift 和 Firebase 的初學者,我需要一個不太復雜的教程或解釋。
謝謝你們
- uikit
- 斯威夫特 5
- 火力基地
uj5u.com熱心網友回復:
所有這一切都假設您已將 Firebase UserAuth 連接到您的應用和設定。
所有用戶都有一個唯一標識他們的 UID,即用戶識別符號。這很容易得到。
//there must be a user signed in
let user = Auth.auth().currentUser
let uid = user.uid
簡而言之,要存盤用戶獨有的資料,請使用 Firestore 將其全部存盤在 uid 下。如果您沒有 Firestore,請開始使用 Firestore。
您保存到 Firestore 的所有資料都必須以字典格式結構化,其中 String 作為鍵,Any 作為值。例如,如果我想為用戶存盤前 3 種最喜歡的冰淇淋口味,您可以這樣做 *注意如果這些檔案和集合不存在,firebase 會自動為您創建這些檔案和集合,所以不要驚慌*:
//First get a reference to the database.
// It is best to have db as a global variable
let db = Firestore.firestore()
let favoriteFlavors: [String: Any] = ["numberOne":flavorOne as Any, "numberTwo":flavorTwo as Any, "numberThree": flavorThree as Any]
//access the collection of users
//access the collection of the currentUser
//create a document called favoriteFlavors
//set the document's data to the dictionary
db.collection("users").collection(uid).document("favoriteFlavors").setData(favoriteFlavors) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
現在,當您想要檢索這些資料時,您確實訪問了 users 集合,即登錄用戶的集合,然后閱讀 favoriteFlavors 檔案——像這樣:
let docRef = db.collection("users").collection(uid).document("favoriteFlavors")
docRef.getDocument { (document, error) in
if let document = document {
print("Document received")
// retrieve the data in the document (a dictionary)
let data = document.data()
} else {
print("Document does not exist")
}
}
因此,如果您想獲得最受歡迎的口味,您可以這樣做:
//Remember that data is a dictionary of String:Any
if let numberOneFlavor = data["numberOne"] as? String {
print("Number one favorite flavor ",numberOneFlavor)
}
當然,這可能會變得更加復雜,但這是您需要了解的堅實基礎。我建議閱讀 Firestore 檔案的添加資料和獲取資料頁面。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/446773.html
