Reputation: 93
I have 2 classes. A class User which contains array of objects of class Item. I want to save object of User in Firebase. What do I need to do for it?
class User: NSObject {
var name: String
var items: [Item]
init(dictionary: [String: Any]) {
self.name = dictionary["name"] as? String ?? ""
}
}
class Item{
var name: String
init(name: String) {
self.name = name
}
}
var user = User(dictionary: [:])
user.name = "Tom"
var item = Item(name: "item1")
user.items.append(item)
let uid = Auth.auth().currentUser?.uid
Database.database().reference().child("users").child(uid).setValue(user)
Upvotes: 0
Views: 70
Reputation: 1934
Save them as firebase object.
class User: NSObject {
var name: String
var items: [Item]
init(dictionary: [String: Any]) {
self.name = dictionary["name"] as? String ?? ""
}
var json: [String: Any] {
return ["name": name, "items": items.map { $0.json }]
}
}
class Item{
var name: String
init(name: String) {
self.name = name
}
var json: [String: Any] {
return ["name": name]
}
}
Database.database().reference().child("users").child(uid).setValue(user.json)
Upvotes: 1