我有一段代码可以从Firebase数据库中提取所有帖子。我正在尝试使代码提取特定用户ID的所有帖子。我数据库的结构是,用户ID具有一组与之关联的帖子ID。
我必须提取所有帖子的代码:
DataService.ds.REF_POSTS.observe(.value, with: { (snapshot) in
self.posts = []
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot {
print("SNAP: \(snap)")
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = Post(postKey: key, postData: postDict)
self.posts.append(post)
}
}
}
self.feedTableView.reloadData()
})
我如何识别当前用户:
_ = Auth.auth().addStateDidChangeListener { (auth,user) in
if let user = user {
let userId = user.uid
print("USER: \(String(describing: userId))")
let newPost = DataService.ds.REF_USERS.child("\(userId)").child("posts")
//print("NEW POST: \(newPost.child)")
newPost.setValue([userPost : true])
}
}
看来我需要到达users对象的子级(帖子),然后循环浏览帖子。如何浏览(并观察更改)与登录用户相关的帖子?
编辑(尝试遍历用户的所有帖子):
_ = Auth.auth().addStateDidChangeListener { (auth,user) in
if let user = user {
let userId = user.uid
print("USER: \(String(describing: userId))")
let newPost = DataService.ds.REF_USERS.child("\(userId)").child("posts")
newPost.observe(.value, with: { (snapshot) in
self.posts = []
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot {
print("ERIC SNAP: \(String(describing: snap.value))")
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = Post(postKey: key, postData: postDict)
self.posts.append(post)
}
}
}
self.feedTableView.reloadData()
})
//print("NEW POST: \(newPost)")
}
}
答案 0 :(得分:0)
获取登录用户帖子的方法如下:
guard let uid = Auth.auth().currentUser?.uid else {
return
}
print("USER ID: \(uid)")
let newPost = DataService.ds.REF_USERS.child("\(uid)").child("posts")
newPost.observe(.value, with: { (snapshot) in
self.posts = []
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot {
let postData = DataService.ds.REF_POSTS.child(snap.key)
postData.observe(.value, with: { (snapshot) in
if let postDict = snapshot.value as? Dictionary<String, AnyObject> {
let key = snapshot.key
let post = Post(postKey: key, postData: postDict)
self.posts.append(post)
}
self.feedTableView.reloadData()
})
}
}
})