问题
I'm porting an android app and using firebase in android it is possible to save a format in this way. How can i do this on Swift? I read that i can store only this kind of data
- NSString
- NSNumber
- NSDictionary
- NSArray
How can I store the obj in atomic operation? It's correct to store every field of the user object in separate action?
Firebase on Android
mDatabaseReferences.child("users").child(user.getUuid()).setValue(user)
回答1:
I generally store objects as dictionaries on firebase. If, within my application, I have a User object, and it has properties as such:
class User {
var username = ""
var email = ""
var userID = ""
var consecutiveDaysLoggedOn = Int()
}
let newUser = User()
newUser.username = "LeviYoder"
newUser.email = "LeviYoder@LeviYoder.com"
newUser.userID = "L735F802847A-"
newUser.consecutiveDaysLoggedOn = 1
I would just store those properties as a dictionary, and write that dictionary to my firebase database:
let userInfoDictionary = ["username" : newUser.username
"email" : newUser.email
"userID" : newUser.userID
"consecutiveDaysLoggedOn" : newUser.consecutiveDaysLoggedOn]
let ref = Database.database().reference.child("UserInfo").child("SpecificUserFolder")
// ref.setValue(userInfoDictionary) { (error:Error?, ref:DatabaseReference) in
ref.setValue(userInfoDictionary, withCompletionBlock: { err, ref in
if let error = err {
print("userInfoDictionary was not saved: \(error.localizedDescription)")
} else {
print("userInfoDictionary saved successfully!")
}
}
Does that address your question?
回答2:
Use
self.ref.child("users").child(user.uid).setValue(["username": username])
来源:https://stackoverflow.com/questions/55750619/how-to-store-custom-object-in-firebase-with-swift