Firebase - 如何获取 observeEventType = Value 中的键值

Firebase - how to get the key value in observeEventType = Value

这是

的后续问题

我有以下数据库结构:

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

我想查询艺术家 ref 并查看艺术家是否已经在数据库中,如果艺术家在数据库中,则获取艺术家密钥(在上面的示例中它将是 -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"只给了我父键"artists"。

如何获得我需要的密钥?

在 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")
    }

这是一个解决方案。

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)
          }
     }
})
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)
    }