无法获取SavedPost

时间:2018-12-20 17:38:38

标签: swift firebase uicollectionview

我的应用程序可以选择保存帖子,以供用户稍后查看。代码是:

func savedPost(for cell: FirstView) {

    guard let indexPath = collectionView.indexPath(for: cell) else { return }
    var post = self.posts[indexPath.item]

    guard let currentuserId = Auth.auth().currentUser?.uid else { return }
    let targetUid = post.user.uid

    guard let postId = post.id else { return }

    let ref = Database.database().reference().child("save_post").child(currentuserId).child(postId)

    if post.hasSaved {

        ref.removeValue { (err, _) in

            if let _ = err {
                showErr(info: NSLocalizedString("failtoUnsave", comment: ""), subInfo: tryLater)
                return
            }

            post.hasSaved = false
            self.posts[indexPath.item] = post
            self.collectionView.reloadItems(at: [indexPath])
        }

    } else {

        let values = ["userId": targetUid]

        ref.updateChildValues(values) { (err, ref) in

            if let _ = err {
                showErr(info: NSLocalizedString("failtoSave", comment: ""), subInfo: tryLater)
            }

            post.hasSaved = true
            self.posts[indexPath.item] = post
            self.collectionView.reloadItems(at: [indexPath])
        }
    }
}

使用此代码,我在“ save_post”中的firebase数据库具有-> currentUseruId-> postid-> postUserId。 在ProfileController上,用户可以从“ savedPost”选项卡查看保存的帖子。代码是:

var savedPosts = [Post]()

fileprivate func fetchSaved() {

    var userIds = [String]()
    var postIds = [String]()

    guard let uid = self.user?.uid else { return }

    let getIDsRef = Database.database().reference().child("save_post").child(uid)
    let query = getIDsRef.queryOrderedByKey()

    query.observeSingleEvent(of: .value) { (snapshot) in

        let dictionary = snapshot.value as? [String: Any]

        dictionary?.forEach({ (key,value) in

            guard let dic = value as? [String: String] else { return }

            postIds.append(key)
            userIds.append(dic["userId"] ?? "")
        })

        var i = 0

        while i < userIds.count {
            self.fetchPostsWithUserIDPostID(userID: userIds[i], postID: postIds[i])
            i += 1
        }
    }
}

fileprivate func fetchPostsWithUserIDPostID(userID: String, postID: String) {

    let getPostRef = Database.database().reference().child("video_list")

    getPostRef.child(userID).child(postID).observeSingleEvent(of: .value, with: { (snapshot) in

        guard let dictionary = snapshot.value as? [String: Any] else { return }

        let ref = Database.database().reference().child("users").child(userID)

        ref.observeSingleEvent(of: .value, with: { (snapshot) in

            guard let dict = snapshot.value as? [String: Any] else { return }

            let user = User(uid: userID, dictionary: dict)
            var post = Post(user: user, dictionary: dictionary)
            post.id = postID

            guard let currentUserUID = Auth.auth().currentUser?.uid else { return }
            Database.database().reference().child("likes").child(postID).child(currentUserUID).observeSingleEvent(of: .value, with: { (snapshot) in

                if let value = snapshot.value as? Int, value == 1 {
                    post.hasLiked = true
                } else {
                    post.hasLiked = false
                }

                post.hasSaved = true

                self.savedPosts.append(post)
                self.savedPosts.sort(by: { (p1, p2) -> Bool in
                    return p1.creationDate.compare(p2.creationDate) == .orderedDescending
                })

                self.collectionView.reloadData()
            })
        })
    })
}

但是,当我单击“ savedPost”选项卡时,没有显示任何帖子。我不知道我的错误在哪里。我在所有重写func collectionView(....)下都有所有必需的代码。我相信错误应该来自上面列出的代码。我真诚地寻求帮助来解决此问题。谢谢。

1 个答案:

答案 0 :(得分:0)

这里可能发生了很多事情。最好在其中放置一些打印语句,以确保1)从数据库中获取的数据看起来像您期望的那样,以及2)您已将其正确解析为Post对象。您是否为CollectionView正确定义了单元格?另外,我看不到您在哪里定义CollectionView的数据源。