我正在使用多个循环从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)
}
}
答案 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)
}
}