从Firebase检索数据而不重复

时间:2020-05-01 17:52:57

标签: ios arrays swift firebase firebase-realtime-database

我正在使用多个循环从Firebase中提取数据,但是这会导致提取重复数据。解决此问题的最佳方法是什么?

func fetchPost(completion: @escaping ([Post])->()) {
    let postRef = self.databaseRef.child("Topics").queryOrdered(byChild: "userId").queryEqual(toValue: "myId")
        postRef.observe(.value, with: { (snapshot) in
            var resultsArray = [Post]()
            var topicIdArray = [Any]()
                for topic in snapshot.children.allObjects as! [DataSnapshot] {
                    let topicId = topic.childSnapshot(forPath: "topicId").value
                    topicIdArray.append(topicId)
                        for element in topicIdArray {
                            let postRef = self.databaseRef.child("posts").queryOrdered(byChild: "topic").queryEqual(toValue: element)
                                postRef.observe(.value, with: { (snapshot) in
                                    for child in snapshot.children {
                                        let post = Post(snapshot: child as! DataSnapshot)
                                        resultsArray.append(post)

                                    }
                                    completion(resultsArray)
                                })

                        }
                }
    }) { (error) in
        print(error.localizedDescription)
    }
}

1 个答案:

答案 0 :(得分:2)

使用“观察单个事件”来避免重复

func fetchPost(completion: @escaping ([Post])->()) {
    let postRef = self.databaseRef.child("Topics").queryOrdered(byChild: "userId").queryEqual(toValue: "myId")
        postRef.observeSingleEvent(.value, with: { (snapshot) in
            var resultsArray = [Post]()
            var topicIdArray = [Any]()
                for topic in snapshot.children.allObjects as! [DataSnapshot] {
                    let topicId = topic.childSnapshot(forPath: "topicId").value
                    topicIdArray.append(topicId)
                        for element in topicIdArray {
                            let postRef = self.databaseRef.child("posts").queryOrdered(byChild: "topic").queryEqual(toValue: element)
                                postRef.observe(.value, with: { (snapshot) in
                                    for child in snapshot.children {
                                        let post = Post(snapshot: child as! DataSnapshot)
                                        resultsArray.append(post)

                                    }
                                    completion(resultsArray)
                                })

                        }
                }
    }) { (error) in
        print(error.localizedDescription)
    }
}
相关问题