如何检索用户帖子,并将其与快照一起添加到表视图-Swift

时间:2018-12-22 02:54:22

标签: swift firebase google-cloud-firestore

因此,我尝试检索数组中的用户关注者信息。然后使用该数组获取每个用户的帖子,然后将其附加到我的表格视图中。在所有这些过程中,我希望添加一个快照侦听器,以便如果用户喜欢某个帖子,该号码将自动更新。当我这样做时,它会附加每个更新,因此在执行某个我不想发生的操作(例如喜欢执行此操作)后,大约会显示5条帖子。有人可以帮我解决这个问题吗?我正在使用Xcode Swift。预先感谢!

class Posts {
    var postArray = [UserPost]()
    var db: Firestore!
    init() {
        db = Firestore.firestore()
    }
    func loadData(completed: @escaping () -> ()) {
        let sevenDaysAgo = Calendar.current.date(byAdding: .day, value: -7, to: Date())
        self.postArray = []
        guard let user = Auth.auth().currentUser else { return }
        let displayUsername = user.displayName
        let userReference = db.collection("Users").document("User: \(displayUsername!)").collection("Connect").document("Following")
        userReference.getDocument { (document, error) in
            if let documentData = document?.data(),
                var FollowerArray = documentData["Following"] as? [String] {
                FollowerArray.append(displayUsername!)
                FollowerArray.forEach {
                    self.db.collection("Users").document("User: \($0)").collection("Posts").whereField("timeOfPost", isGreaterThanOrEqualTo: sevenDaysAgo!)
                        .addSnapshotListener { (querySnapshot, error) in
                            guard error == nil else {
                                print("*** ERROR: adding the snapshot listener \(error!.localizedDescription)")
                                return completed()
                            }
                            //self.postArray = []
                            // there are querySnapshot!.documents.count documents in the posts snapshot
                            for document in querySnapshot!.documents {
                                let post = UserPost(dictionary: document.data())
                                self.postArray.append(post)
                            }
                            completed()
                    }
                }
}

1 个答案:

答案 0 :(得分:1)

我建议采用其他方法,并让Firestore告诉您何时添加,修改或删除了子节点(帖子)。根据您的代码,您的结构如下所示:

Users
  uid
    //some user data like name etc
    Posts
      post_0
        likes: 0
        post: "some post 0 text"
      post_1
        likes: 0
        post: "text for post 1"

让我们有一门课程来存储帖子

class UserPostClass {
    var postId = ""
    var postText = ""
    var likes = 0

    init(theId: String, theText: String, theLikes: Int) {
        self.postId = theId
        self.postText = theText
        self.likes = theLikes
    }
}

,然后是一个数组,用于保存UserPosts,它将成为tableView dataSource

var postArray = [UserPostClass]()

然后..我们需要一段代码来完成三件事。首先,当新帖子添加到数据库中时(或当我们第一次启动应用程序时),请将其添加到dataSource数组中。其次,修改帖子后,例如另一个用户喜欢该帖子,请更新数组以反映新的喜欢计数。第三,如果帖子被删除,请将其从数组中删除。这是完成全部三个操作的代码……

func populateArrayAndObservePosts() {
    let uid = "uid_0" //this is the logged in user
    let userRef = self.db.collection("users").document(uid)
    let postsRef = userRef.collection("Posts")
    postsRef.addSnapshotListener { documentSnapshot, error in
        guard let snapshot = documentSnapshot else {
            print("err fetching snapshots")
            return
        }

        snapshot.documentChanges.forEach { diff in
            let doc = diff.document
            let postId = doc.documentID
            let postText = doc.get("post") as! String
            let numLikes = doc.get("likes") as! Int

            if (diff.type == .added) { //will initially populate the array or add new posts
                let aPost = UserPostClass(theId: postId, theText: postText, theLikes: numLikes)
                self.postArray.append(aPost)
            }

            if (diff.type == .modified) { //called when there are changes
                //find the post that was modified by it's postId
                let resultsArray = self.postArray.filter { $0.postId == postId }
                if let postToUpdate = resultsArray.first {
                    postToUpdate.likes = numLikes
                }
            }

            if (diff.type == .removed) {
                print("handle removed \(postId)")
            }
        }
        //this is just for testing. It prints all of the posts
        // when any of them are modified
        for doc in snapshot.documents {
            let postId = doc.documentID
            let postText = doc.get("post") as! String
            let numLikes = doc.get("likes") as! Int
            print(postId, postText, numLikes)
        }
    }
}