像按钮一样喜欢instagram崩溃后按

时间:2018-08-31 01:04:24

标签: swift firebase firebase-realtime-database

我向我的应用程序添加了新选项,用户可以喜欢这些地方,但是当我按类似Button的按钮时,我会崩溃[线程1:致命错误:在展开一个可选值时意外发现nil]

代码: tableViewCell按钮

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


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

                if error == nil {
                    ref.child("Restaurant").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 this place"

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

                                self.likeBtn.isHidden = true
                                self.unlikeBtn.isHidden = false
                                self.likeBtn.isEnabled = true
                                print("Likes")
                            }
                        }
                    })
                }
            })
        }


    })

    ref.removeAllObservers()
}

错误屏幕截图 enter image description here

第二个屏幕截图 enter image description here

有人可以帮助我吗,谢谢!

1 个答案:

答案 0 :(得分:0)

let updateLikes: [String : Any] = ["peopleWhoLike/\(keyToPost)" : Auth.auth().currentUser!.uid]

可能没有currentUser->强制拆开像崩溃您的应用程序一样,我会尽可能避免它们。 您在哪里验证当前用户?

您如何登录用户: data image

然后在您的代码之前,我要做类似的事情:

guard let userUID = Auth.auth().currentUser?.uid else {
return
}