【问题标题】:Firebase comments not appearing on databaseFirebase 评论未出现在数据库中
【发布时间】:2018-08-24 16:32:04
【问题描述】:

我是 Firebase 的新手。我正在使用斯威夫特。我想将用户的 cmets 存储在我的数据库中,但是 Firebase 上似乎没有显示任何内容。我的代码有问题吗? 感谢您的帮助。

@IBAction func OnSubmitTouched(_ sender: UIButton) {
    if (textField.text != ""){

       let ref = Database.database().reference()
       let commentsReference = ref.child("comments")
       let newCommentID = commentsReference.childByAutoId().key
       let newCommentReference = commentsReference.child(newCommentID)
        guard let currentUser = Auth.auth().currentUser else {
            return
        }
        let currentUserID = currentUser.uid
        newCommentReference.setValue(["uid": currentUserID, "commentText": textField.text!]) { (error, ref) in
            if error != nil {
               // ProgressHUD.showError(error!.localizedDescription)
                return
            }
        }

【问题讨论】:

  • 弹出的第一件事是你现在没有对error 做任何事情。如果您在调试器中单步执行代码,error 是否有值?如果是这样,该值是否解释了为什么没有向数据库写入任何内容?
  • @FrankvanPuffelen 我通过放置断点进行了调试。调试器无法通过第一个 return 语句,这是受保护的语句 let currentUser = ...。问题是,在我的应用程序中,我不要求用户注册或登录,他们只是直接发布他们的厘米。我不需要使用 Auth.auth() 函数吗?原因是在后期我不希望所有相同的 cmets 出现在不同的帖子上。我想根据用户选择的帖子显示用户的 cmets。很抱歉占用您的时间我是 Firebase 的新手。
  • 听起来您没有当前用户(您可能希望通过单击其下方的编辑链接将其添加到您的帖子中)。您可能希望使用身份验证状态侦听器来检测用户,如第一个示例所示:firebase.google.com/docs/auth/ios/…
  • @FrankvanPuffelen 我不希望用户填写注册页面或登录到他们的帐户来发表评论。这仍然是我应该做的吗?
  • 这不是一个答案,而是一个建议;您没有使用密钥,因此不需要以这种方式获取;只需 let cmetsRef = ref.child("cmets").childByAutoId() 然后 cmetsRef.setValue...。这只是缩短了一点。 @FrankvanPuffelen 很到位。用户应该经过身份验证才能发布 cmets,否则您将不知道评论来自谁/来自何处。如果您希望用户匿名,请查看Anonymous Authentication

标签: swift firebase firebase-realtime-database firebase-authentication


【解决方案1】:

听起来您希望用户能够发布 cmets。用户可以选择登录,在这种情况下,您还想存储他们的 UID。

以极其简单的方式(我也不是 Swift 专家)是:

    var currentUserID = "anonymous"
    if let currentUser = Auth.auth().currentUser {
        currentUserID = currentUser.uid
    }
    newCommentReference.setValue(["uid": currentUserID, "commentText": textField.text!]) { (error, ref) in
        if error != nil {
            print(error!.localizedDescription)
            return
        }
    }

现在uid 属性将具有发表评论的用户的 UID,如果用户未登录,则为 "anonymous"

【讨论】:

  • 谢谢杰。固定的。下次我搞砸时,请随时编辑。 ;-)
  • 我认为您的意思是 currentUserID = currentUser.uid 而不仅仅是 currentUser。但无论哪种方式,非常感谢你它现在有效!祝你有美好的一天!
猜你喜欢
  • 2021-07-24
  • 2011-12-28
  • 2016-04-20
  • 2012-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-13
相关资源
最近更新 更多