如何使用Swift在Firebase中存储自定义对象? [英] How to store custom object in Firebase with Swift?
问题描述
我正在移植一个android应用程序,并在android中使用firebase,因此可以通过这种方式保存格式.我该如何在Swift上执行此操作?我读到我只能存储这种数据
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
如何在原子操作中存储obj?将用户对象的每个字段存储在单独的操作中是正确的吗?
How can I store the obj in atomic operation? It's correct to store every field of the user object in separate action?
Android上的Firebase
Firebase on Android
mDatabaseReferences.child("users").child(user.getUuid()).setValue(user)
推荐答案
我通常将对象作为字典存储在Firebase上.如果在我的应用程序中有一个User对象,并且它具有如下属性:
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
我只是将这些属性存储为字典,然后将该字典写入我的Firebase数据库:
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!")
}
}
这能解决您的问题吗?
这篇关于如何使用Swift在Firebase中存储自定义对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!