我正在尝试初始化我的“收藏夹视图模型”,该模型包含一个[users]列表以及一个包含数据的firebase snap。
这是集合视图模型代码:
typealias JSON = [String:Any]
class HomeDataSource: Datasource {
var users: [User]
init?(with snapshot:DataSnapshot) {
var users = [User]()
guard let snapDict = snapshot.value as? [String: [String:Any]] else {return nil}
for snap in snapDict {
guard let user = User(dict: snap.value) else {continue}
users.append(user)
}
self.users = users
}
}
用户模型:
struct User {
let name: String
let username: String
init?(dict: JSON) {
guard let name = dict["name"] as? String,
let email = dict["email"] as? String
else {return nil}
self.name = name
self.username = email
}
}
Firebase快照:
Snap (users) {
8CVeHMNHI6hZAWj1zhGHEjPwYYz1 = {
email = "Silviu@isidors.sjsj";
name = Bshdjdj;
};
9CuqgR4Es7TOPPJQEpSnQXlfYnm1 = {
email = "Test@silviu.com";
name = "Test@silviu.com";
};
DBqGWlpdJKME570euqUz2rqI5Z83 = {
email = "Test@test.test";
name = Test;
};
}
获取功能:
func fetchUser() {
let ref = Database.database().reference().child("users")
ref.observe(.childAdded, with: { (snapshot) in
let user = User(dict: snapshot.value as! JSON)
self.users.append(user!)
print(self.users)
let new = HomeDataSource(with: snapshot)
print(new)
DispatchQueue.main.async(execute: {
self.datasource = new
self.collectionView?.reloadData()
})
}, withCancel: nil)
}
现在,我从Firebase获得了一系列用户,但是我的收藏夹视图不会更新。
我的问题是我应该如何更新我的“收藏夹视图模型”和“获取功能”,以便它可以从Firebase获取数据并正确填充收藏夹视图?
答案 0 :(得分:0)
所以问题出在我定位的节点上。删除了“ child("users")
”表单获取功能,并使用uid将整个用户节点作为目标。然后,当我在[String:[String:Any]]中将其投射时,我正在循环执行snapshot.value,因为每个snapshot.value
看起来都像这样(key: "vijwUkzAlbgcqjAammfy0JuVMB33", value: ["name": Silviu, "email": Office@isidors.com])
:最后,我这样更新了HomeDataShource类:>
class HomeDataSource: Datasource {
var users: [User]
init(with snapshot:DataSnapshot) {
var users = [User]()
let snapDict = snapshot.value as? [String:[String:Any]]
for snap in snapDict! {
guard let user = User(snap: snap.value) else {continue}
users.append(user)
}
self.users = users
}