【问题标题】:Why does snapshot.value as dictionary return nil?为什么snapshot.value作为字典返回nil?
【发布时间】:2020-11-05 07:54:09
【问题描述】:

我是 swift 和 firebase 的新手,我想知道为什么我会收到 snapshot.value 作为? NSDictionary 为 nil,即使用户已登录。

 let uid = Auth.auth().currentUser?.uid
        
        Database.database().reference().child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
            print(snapshot.value as? NSDictionary)
            if let value = snapshot.value as? NSDictionary{
                self.title = value["firstname"] as? String
                print("o")
            }
            print(self.title)
            
        }, withCancel: { (error) in
            print(error.localizedDescription)
        })
    }
//I want it to return the name of the user (Ben) as the title of the navigation bar, but instead it returns nil

数据库是:

    {
  "users" : {
    "-MBzED86cdVbvBNcYdpY" : {
      "email" : "bb@gmail.com",
      "firstname" : "benjamin",
      "username" : "bb"
    },
    "-MBzEWEQ3cX6d5aJOByR" : {
      "email" : "bslou.row@gmail.com",
      "firstname" : "bslou",
      "username" : "bbbslou.row"
    }
}
}

当我打印快照时,我的程序返回“Snap (mDNGl4fQXEMx1wPnjGuhILp5f8j1)”

【问题讨论】:

  • print(type(of: snapshot.value)) 显示什么?并避免在 Swift 中使用 NS... 集合类型。
  • 它显示FIRDataSnapshot,好的,我将更改为字典
  • 请编辑问题以显示您希望此查询返回的数据。由于看不到数据库的内容,也看不到uid的具体值,所以也无能为力。查询的结果只是告诉你在你查询的位置没有数据。
  • 我编辑了@DougStevenson 的问题,我也展示了数据库
  • 当我打印快照时,我只得到 id

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


【解决方案1】:

数据库中“用户”下的子键不是 Firebase 身份验证用户 ID。它们看起来像随机生成的推送 ID(又名“自动 ID”)。您使用 UID 的查询根本不会找到这些孩子。请注意,您的快照 ID 根本与数据库不匹配。快照是空的 - 它不包含任何数据。

您将不得不返回创建这些子代的代码并使用用户的实际 UID,而不是使用自动 ID。

【讨论】:

    猜你喜欢
    • 2018-12-14
    • 2019-03-10
    • 2014-11-11
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多