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

后端 未结 3 750
礼貌的吻别
礼貌的吻别 2020-12-06 08:39

This is a follow up question to Firebase - proper way to structure the DB

I have the following DB structure:

\"artists\" : {
  \"-KKMkpA22PeoHtBAPyKm         


        
相关标签:
3条回答
  • 2020-12-06 09:10
    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)
        }
    
    0 讨论(0)
  • 2020-12-06 09:33

    In if condition, you need to get allKeys to get "-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")
        }
    
    0 讨论(0)
  • 2020-12-06 09:35

    Here's a solution.

    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)
              }
         }
    })
    
    0 讨论(0)
提交回复
热议问题