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

时间:2016-06-16 08:15:31

标签: ios swift firebase firebase-realtime-database

这是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”只给我父键“艺术家”。

如何获得我需要的密钥?

3 个答案:

答案 0 :(得分:4)

如果条件允许,你需要让所有人获得&#34; -KKMkpA22PeoHtBAPyKm&#34; ......

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

答案 1 :(得分:3)

这是一个解决方案。

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

答案 2 :(得分:0)

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