【问题标题】:Is there anyway to access only the value of a dictionary in a child?无论如何只能访问孩子中字典的值吗?
【发布时间】:2017-09-13 23:20:36
【问题描述】:

在 Swift 的 Firebase 数据库中,有没有办法从字典中访问值(作为字符串)。每个孩子都有一个键:值对。例如:

users
|-- Bob
    |-- Bob@gmail.com: "BOBBBBY"

有没有办法以字符串的形式访问"BOBBBBY"? 我是 Swift 新手,因此不胜感激。

【问题讨论】:

  • 这个问题真的没有意义!能否请您添加更多信息!?
  • 您是否查看过 Firebase 官方文档或getting started guide?
  • @DávidPásztor 对混乱感到抱歉。是的,我读过它们。每次我使用 child.value 时,它​​都会将数据作为字典而不是字符串返回。我只想将“BOBBY”作为字符串
  • @Siyavash 那里
  • @MichaelR。解决混淆的最简单方法是分享minimal possible code that reproduces where you are stuck。

标签: swift dictionary firebase firebase-realtime-database


【解决方案1】:

Firebase 数据库文档中的示例

直接取自https://firebase.google.com/docs/database/ios/read-and-write

let userID = Auth.auth().currentUser?.uid
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
    // Get user value
    let value = snapshot.value as? NSDictionary
    let username = value?["username"] as? String ?? "" // <<< this line
    let user = User.init(username: username)

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

为您更新

如果用户下需要多个字段:

ref.child("users").child("Bob").observeSingleEvent(of: .value, with: { (snapshot) in
    let value = snapshot.value as? NSDictionary
    let emailValue = value?["Bob@gmail.com"] as? String ?? ""
    // do more...
}

...或者如果您只需要一个值:

ref.child("users").child("Bob").child("Bob@gmail.com").observeSingleEvent(of: .value, with: { (snapshot) in
    if let value = snapshot.value as? String {
        // use the value...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2022-11-22
    相关资源
    最近更新 更多