使用Firebase,我想异步获取数据,然后在TableView上显示它,但是某些数据在TableView上重复。我认为这是因为我在For语句中使用了闭包,但是我不确定应该在何处调用它。
我试图在Dispatchqueue.main.async中调用setDataToArray,但是它不起作用。
Class PostTableViewController: UITableViewController {
let db = Firestore.firestore()
var postArray: [Post] = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
SVProgressHUD.show()
configureTableview()
setDataToArray()
}
func setDataToArray() {
retrievePost() { (posts) in
print(posts!)
for post in posts! {
self.postArray.append(post)
}
print(self.postArray)
self.tableView.reloadData()
SVProgressHUD.dismiss()
}
}
func retrievePost(completion: @escaping ([Post]?) -> Void) {
var posts = [Post]()
let postsColRef = db.collection("posts").order(by: "createdAt")
postsColRef.getDocuments() { (querySnapshot, error) in
if let error = error {
print("Document data: \(error)")
} else {
for document in querySnapshot!.documents {
let data = document.data()
let userId = data["userId"] as? String
let postImage = data["postImageURL"] as? String
let postText = data["postText"] as? String
let createdAt = data["createdAt"] as? String
let numberOfLike = data["numberOfLike"] as? Int
let docRef = self.db.collection("users").document(userId!)
docRef.getDocument() { (document, error) in
if let document = document, document.exists {
let data = document.data()!
let userName = data["userName"] as? String
let userImage = data["userImageURL"] as? String
let post = Post(
userId: userId!,
userName: userName!,
userImageURL: userImage!,
postImageURL: postImage!,
postText: postText!,
createdAt: createdAt!,
numberOfLike: numberOfLike!)
print(post)
posts.append(post)
completion(posts)
}
}
}
}
}
}
@IBAction func cameraButtonPressed(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "homeToChooseImage", sender: nil)
}
}
extension PostTableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
let post = postArray[indexPath.row]
let postImageURL = URL(string: post.postImageURL)
do {
let data = try Data(contentsOf: postImageURL!)
cell.postImage.image = UIImage(data: data)
}catch let err {
print("Error : \(err.localizedDescription)")
}
let userImageURL = URL(string: post.userImageURL)
do {
let data = try Data(contentsOf: userImageURL!)
cell.userImage.image = UIImage(data: data)
}catch let err {
print("Error : \(err.localizedDescription)")
}
cell.postText.text = post.postText
cell.userName.text = post.userName
cell.createdAt.text = post.createdAt
cell.postLikeButton.titleLabel?.text = "\(post.numberOfLike) Likes"
return cell
}
}
我猜我在哪里称“完成(帖子)”是错误的。 我应该在哪里称呼它呢?