按下“赞”按钮后,如何将喜欢记录在firebase中?

时间:2019-07-19 14:46:45

标签: swift firebase firebase-realtime-database

我一直在努力争取将喜欢的人记录在Firebase中。 (将“喜欢'UID的人”输入到“他喜欢的人的孩子推荐人”中。)

如果已按一下操作,我就已经连接了插座,并且具有将其插入Firebase的代码,但是在某个地方,我会产生nil作为可选参数。

    @IBAction func likePressed(_ sender: Any) {
    self.like.isEnabled = false
    let ref = Database.database().reference()
    let keyToPost = ref.child("likes").childByAutoId().key

    ref.child("people").child(self.postID).observeSingleEvent(of: .value, with:  {(snapshot) in

        if let people = snapshot.value as? [String: AnyObject] {
            let updateLikes: [String: Any] = ["peopleWhoLike/\(keyToPost)" : Auth.auth().currentUser!.uid]
            ref.child("people").child(self.postID).updateChildValues(updateLikes, withCompletionBlock: { (error, rerr) in

                if error == nil {
                       ref.child("people").child(self.postID).observeSingleEvent(of: .value, with: { (snap) in
                        if let properties = snap.value as?[String: AnyObject]{
                            if let likes = properties["peopleWhoLike"] as? [String : AnyObject] {
                                let count = likes.count
                                self.likeLabel.text = "\(count) Likes"

                            let update = ["likes" : count]
                                ref.child("people").child(self.postID).updateChildValues(update)


                            }

                        }
                    })
                }
            })

        }

    })

    ref.removeAllObservers()



}

////////////////内部首页覆盖功能表视图:

 cell.postID = self.people[indexPath.row].postID

这是Json数据库结构:

"people" : {
"9RYUttVhCzXKs6H1XnZ63TZ8Dun2" : {
  "Coordinates" : {
    "latitude" : 15.78583,
    "longitude" : -4.406417
  },
  "Education" : "CS",
  "PhotoPosts" : "https://firebasestorage.googleapis.com/v0/b/daylike-2f938.appspot.com/o/images%2FPhotoPosts?alt=media&token=ac9e574f-b55f-4bf0-b75b-79b877a86480",
  "caption" : 1563439869418,
  "users" : "nane19@aol.com"
},
"K1eqsVZfKGgIf0sS1UZcPNxY62x1" : {

在Firebase数据库的最后,在用户Ronald的提示下,将列出喜欢他的人(更准确地说是他们的uid)。那将在新的子postID下。

1 个答案:

答案 0 :(得分:0)

所以我发现了错误。数据库没有子postID,该子ID应与uid相同。登录后添加该子项后,该错误已修复。