如何在表格视图中正确排序我的帖子?到目前为止,我有这个:
func observePosts(completion: @escaping (PostModel) -> Void) {
let REF_QUERY = REF_POST.queryOrdered(byChild: "postDate")
REF_QUERY.observe(.childAdded) { (snapshot) in
print(snapshot)
guard let dic = snapshot.value as? [String: Any] else { return }
let newPost = PostModel(dictionary: dic, key: snapshot.key)
completion(newPost)
}
}
Snap结果为:User1-Post1,User2-Post2,User1-Post3,User2-Post4 ..似乎正确。
以上功能将在我的ViewController中使用:
func loadPosts() {
activityIndicatorView.startAnimating()
PostApi.shared.observePosts { (post) in
self.fetchUser(uid: post.uid!, completed: {
self.posts.insert(post, at: 0)
self.activityIndicatorView.stopAnimating()
self.tableView.reloadData()
self.tableView.setContentOffset(CGPoint.zero, animated: true)
})
}
}
结果按正确的顺序及时发布,但按发布了以下内容的用户进行了排序:
用户1-帖子1,用户1-帖子3,用户2-帖子2,用户2-帖子4。
新的排序发生在调用fetchUser函数之后。
func fetchUser(uid: String, completed: @escaping () -> Void) {
UserApi.shared.observeUser(uid: uid) { (user) in
self.users.insert(user, at: 0)
completed()
}
}
为什么在这里发生度假村?
编辑:这是我的UserAPI观察用户函数:
func observeUser(uid: String, completion: @escaping (UserModel) -> Void) {
REF_USERS.child(uid).observeSingleEvent(of: .value) { (snapshot) in
guard let dic = snapshot.value as? [String: Any] else { return }
let newUser = UserModel(dictionary: dic)
completion(newUser)
}
}