从firebase获取的图像在添加到tableViewCells的过程中会重复吗



以下代码从firebase获取图像,但错误地复制了两个图像。我认为这是由于self.tableView.reloadData()的放置,我尝试过的放置都不起作用。有人能给我建议吗?

func fetchAllUsersImages() {
print("inside func")
self.ref.child("Posts").child(self.userID).child(self.postNum).observe(.childAdded, with: { snapshot in
if let snapShotValue = snapshot.value as? [String: String] {
for (_, value) in snapShotValue {
if let imageURL = URL(string: value) {
print(imageURL, "image url here")
do {
let imageAsData = try Data(contentsOf: imageURL)
let image = UIImage(data: imageAsData)
let ImageObject = Image()
ImageObject.image = image
self.arrayOfImgObj.append(ImageObject)
} catch {
print("imageURL was not able to be converted into data")
}
}
}
}
})
}

请确保在开始调用函数时清除数组,因为您正在将数据附加到数组中。其次,在完成for循环后重新加载表。

func fetchAllUsersImages() {
self.arrayOfImgObj.removeAll() // clean the array
self.ref.child("Posts").child(self.userID).child(self.postNum).observe(.childAdded, with: { snapshot in
if let snapShotValue = snapshot.value as? [String: String] {
for (_, value) in snapShotValue {
}
tableView.reloadData() // reload view
}
})
}

最新更新