ios - 无法使用Swift 5(iOS)从Firebase数据库获取和打印单个值

标签 ios swift firebase firebase-realtime-database

目的:尝试将Firebase Realtime数据库中的“电子邮件”值打印到XCode 11控制台中。请参阅提供的代码和JSON摘录。

注释:这个问题似乎很明显,但是尝试了包括Swift Get Specific Value From Firebase Database和Firebase文档在内的一些建议后,我似乎仍然错过了一些东西。

代码:

func updateRiskValue() {

    var databaseReference: DatabaseReference!

    databaseReference = Database.database().reference()

    let currentUser = Auth.auth().currentUser
    databaseReference.child("users").child((currentUser?.uid)!).child("email").observeSingleEvent(of: .value, with: { (snapshot) in

        let value = snapshot.value as? NSDictionary

        let valueRisk = value?["email"] as? String ?? ""

        print(valueRisk)

    }) {(error) in
        print(error.localizedDescription)
    }
}

@IBAction func riskSlider(_ sender: UISlider) {

    updateRiskValue()

}

JSON摘录:
"users" : {
"ihhqjBDfIYeyl5QqsnFl1LVrXRG3" : {
  "email" : "alexander@gmail.com",
  "isCheckedCount" : 3,
  "kycitems" : {
    "Attach Government Documents" : {
      "isChecked" : false
    },
    "Client Knowledge" : {
      "isChecked" : true
    },
    "Contact Information" : {
      "isChecked" : true
    },
    "PEP Check" : {
      "isChecked" : true
    },
    "Risk Assessment" : {
      "isChecked" : true
    },
    "Source of Wealth" : {
      "isChecked" : true
    },
    "Transit Account Holders" : {
      "isChecked" : true
    },
    "Transit Account Numbers" : {
      "isChecked" : false
    }
  },
  "password" : "123123",
  "riskValue" : "1",
  "todos" : {
    "Hello" : {
      "isChecked" : false
    }

最佳答案

您将添加一个观察者到/Users/$uid/email,因此您获得的snapshot仅包含email属性的值。但是,您将其视为字典,这解释了为什么您的代码不起作用。

要解决此问题,请从

databaseReference.child("users").child((currentUser?.uid)!).child("email").observeSingleEvent(of: .value, with: { (snapshot) in

    let valueRisk = snapshot.value as? String
    print(valueRisk)

}) {(error) in
    print(error.localizedDescription)
}

关于ios - 无法使用Swift 5(iOS)从Firebase数据库获取和打印单个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61044002/

相关文章:

ios - 导航栏颜色

ios - Swift 自定义后退按钮和目的地

iOS Swift Firebase 存储错误 "No default Storage bucket found"

ios - 从 firebase 获取用户数据?

swift - 无法将类型 '()' 的值转换为预期的参数类型 '(() -> Void)?'

ios - 如何在 Swift 中使用自定义图像作为 UIButton

ios - 从ActionSheet移除红色破坏性按钮

swift - 无法在 Swift/Cocoa/NextStep 中将 JS 注入(inject) WKWebView/将 WKWebView 中网页上的用户选择推送到 Swift/Cocoa

swift - 通过具有关联值的枚举属性过滤项目数组

ios - 以编程方式将 uibutton 添加到详细 View