让所有用户在Firebase中获得相同的孩子(Swift)

时间:2016-07-20 10:13:20

标签: ios swift firebase firebase-realtime-database

我目前正在Firebase中构建应用,我想让所有用户获得菠萝率。

这是树:

user1: uid1 {
  fruits: {
    apple: 3
    pineapple: 5
  }
}

user2: uid2 {
  fruits: {
    apple: 4
    pineapple: 2
  }
}

我试过这段代码:

var ref = FIRDatabase.database().reference()
ref.queryOrderedByChild("fruits")
            .observeSingleEventOfType(.Value, withBlock: { (snapshot) in
                if ( snapshot.value is NSNull ) {
                    print("not found")
                } else {
                    for child in snapshot.children {
                        let rate = child.value["pineapple"] as! String
                        print(rate)
                    }
                }
            })

但它给我一个解开Nil的错误。

结构图片:

enter image description here

3 个答案:

答案 0 :(得分:2)

这应该是这样的

  var ref = FIRDatabase.database().reference()
     ref.queryOrderedByChild("user2")
        .observeSingleEventOfType(.Value, withBlock: { (snapshot) in
            if snapshot.exists() {
                for child in (snapshot.value?.allValues)! {
                    if let fruits = child["Fruits"] as? [String:String]{
                        let rate = fruits["pineapple"]
                        print(rate)
                    }
                }
            }
        })

答案 1 :(得分:0)

这似乎只需要一个深层次的查询?

    let ref = self.myRootRef.child("parent_node")

    ref.queryOrderedByChild("Fruits/pineapple").observeSingleEventOfType(.Value, withBlock: { 
       snapshot in

        if ( snapshot.value is NSNull ) {
            print("not found")
        } else {
            for child in snapshot.children {

                let key = child.key as String
                let dict = child.value["Fruits"] as! NSDictionary
                let pineapple_count = dict["pineapple"] as! Int
                print("key = \(key)  count = \(pineapple_count)")

            }
        }
    })

,输出

key = uid_1  count = 1
key = uid_0  count = 3
key = uid_2  count = 21

答案 2 :(得分:0)

尝试下面的代码(Xcode 8.3.3,Swift 3和Firebase 3)

   var ref = Database.database().reference().child("fruits")

   ref.observeSingleEvent(of: .value, with: {                
                (snapshot) in
         if let fruitPost = snapshot.value as? Dictionary<String,AnyObject> {
                 for(key, value) in fruitPost {
                      if let fruitData = value as? Dictionary<String,AnyObject> {
                             if let fruits = fruitData["pineapple"] as? String{
                                     let rate = fruits
                                        print(rate)
                                   }            
                              }
                          }
                    }

Goodluck伙伴!