Firebase Firestore查询帖子和快照

时间:2019-02-26 18:41:57

标签: ios swift firebase google-cloud-firestore

所以这里我有一个功能,当标签出现时,帖子将从Google的Firebase Firestore加载。通过首先获取已登录用户正在关注的所有用户的列表,然后获取该列表中每个用户的帖子来完成此操作。我想发生的事情是加载该帖子,然后每当用户喜欢一个帖子或对该帖子执行另一项操作时,我都希望增加likeCount。我通过快照执行此操作,问题是,当我喜欢某个帖子或类似的内容时,tableview会跳来跳去,似乎加载和显示的帖子彼此之间有所不同。例如,如果我喜欢列表中第一位的帖子,似乎我实际上是在喜欢更靠后的帖子。我感觉这是由于快照造成的。任何帮助都将是惊人的。预先谢谢你。

func LoadTimeline(completed: @escaping () -> ()) {
    let fourteenDaysAgo = Calendar.current.date(byAdding: .day, value: -14, to: Date())
    guard Auth.auth().currentUser != nil else { return }
    let userReference = db.collection("Users").document("User: \(userUID)").collection("Connect").document("Following")

    userReference.getDocument { (document, error) in
        if document!.exists == true {
            if let documentData = document?.data(),
                var FollowerArray = documentData["Following"] as? [String] {
                FollowerArray.append(self.userUID)
                FollowerArray.forEach {
                    let documentPathForUserPosts = self.db.collection("Users").document("User: \($0)").collection("Posts").whereField("timeOfPost", isGreaterThanOrEqualTo: fourteenDaysAgo!)

                    self.userPost = []
                    documentPathForUserPosts.getDocuments() { (querySnapshot, err) in
                        if let err = err {
                            print("Error getting documents: \(err.localizedDescription)")
                            return completed()
                        } else {
                            for document in querySnapshot!.documents {
                                if self.userPost.count % 3 == 0 && self.userPost.count != 0 {
                                    let adElement = UserPost(userUID: "", userName: "", userProfileImage: "", spotName: "", spotCity: "", spotProvince: "", postTextContent: "", postDocumentID: "", spotDocumentID: "", spotAddress: "", spotCountry: "", tag: "", numberOfAdds: 0, numberOfLikes: 0, numberOfComments: 0, spotLatCoord: 0.0, spotLongCoord: 0.0, date: "", imageURL: "", imageURLUUID: "", timeOfPost: Timestamp(), isAd: true)
                                    print("Ad Appened: Current UserPost count: ", self.userPost.count)
                                    self.userPost.insert(adElement, at: self.userPost.count)
                                }
                                self.userPost.append(UserPost(dictionary: document.data()))
                            }
                        }
                    }

                    documentPathForUserPosts.addSnapshotListener { documentSnapshot, error in
                        guard let snapshot = documentSnapshot else {
                            print("Error fetching snapshots!")
                            return completed()
                        }
                        snapshot.documentChanges.forEach { diff in
                            let doc = diff.document
                            let postId = doc.documentID
                            let postText = doc.get("postTextContent") as! String
                            let numLikes = doc.get("numberOfLikes") as! Int
                            let numAdds  = doc.get("numberOfAdds") as! Int
                            let numComments = doc.get("numberOfComments") as! Int

                            if (diff.type == .modified) {
                                self.tableView.beginUpdates()
                                let index = self.userPost.index(where: { (item) -> Bool in
                                    item.postDocumentID == postId
                                })

                                let userPostArray = self.userPost[index!]
                                userPostArray.numberOfLikes    = numLikes
                                userPostArray.numberOfAdds     = numAdds
                                userPostArray.postTextContent  = postText
                                userPostArray.numberOfComments = numComments
                                }
                            self.tableView.endUpdates()
                        }
                        completed()
                    }
                }
            }
        } else {
            print("User does not follow anyone, have any posts of their own")
            self.activityIndicator.stopAnimating()
            if self.userPost.count >= 1 {
                self.tableView.backgroundView = nil
                self.tableView.separatorStyle  = .none
                self.noDataLabel.isHidden = true
            } else {
                self.noDataLabel.isHidden = false
                self.noDataInTable()
            }
        }
    }
}

0 个答案:

没有答案