【问题标题】:Firebase - how to get the key value in observeEventType = ValueFirebase - 如何获取observeEventType = Value中的键值
【发布时间】:2016-10-17 15:17:06
【问题描述】:

这是Firebase - proper way to structure the DB的后续问题

我有以下数据库结构:

"artists" : {
  "-KKMkpA22PeoHtBAPyKm" : {
    "name" : "Skillet"
  }
}

我想查询艺术家参考,看看艺术家是否已经在数据库中,如果艺术家在数据库中,获取艺术家密钥(在上面的例子中,它是 -KKMkpA22PeoHtBAPyKm)。

我试过了:

artistsRef.queryOrderedByChild("name").queryEqualToValue("Skillet").observeEventType(.Value, withBlock: { (snapshot) in
        if snapshot.exists() {
            print("we have that artist, the id is \(snapshot.key)")
        } else {
            print("we don't have that, add it to the DB now")
        }
    })

但是“snapshot.key”只给了我“艺术家”的父键。

我怎样才能得到我需要的钥匙?

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    if 条件下,需要获取 allKeys 才能获取 "-KKMkpA22PeoHtBAPyKm" ...

        if snapshot.exists() {
            for a in (snapshot.value?.allKeys)!{
                print(a)
            }
        } else {
            print("we don't have that, add it to the DB now")
        }
    

    【讨论】:

    • 它不会为我编译 - 而是:for a in (snapshot.value?.allKeys)! {
    【解决方案2】:

    这里有一个解决方案。

    let ref = self.myRootRef.childByAppendingPath("artists")
    
    ref.queryOrderedByChild("name").queryEqualToValue("Skillet")
         .observeEventType(.Value, withBlock: { snapshot in
    
         if ( snapshot.value is NSNull ) {
              print("Skillet was not found")
         } else {
              for child in snapshot.children {   //in case there are several skillets
                   let key = child.key as String
                   print(key)
              }
         }
    })
    

    【讨论】:

    • 您可以将snapshot.value is NSNull替换为!snapshot.exists()
    【解决方案3】:
    You can get the Keys with the help of Dictionary itself.
    
        Database.database().reference().child("artists").observe(.value, with: { (snapshot) in
            if snapshot.exists() {
                if let artistsDictionary = snapshot.value as? NSDictionary {
                    for artists in artistsDictionary.keyEnumerator() {
                        if let artistsKey = artists as? String {
                            print(artistsKey) // Here you will get the keys.
                        }
                    }
                }
            } else {
                print("no data")
            }
        }) { (error) in
            print(error)
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      相关资源
      最近更新 更多