Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase - retrieve all child keys and child values into separate arrays in Swift

Is there any way to retrieve all the keys in a child, put them into array, and then retrieve the values for the keys and put it into another array?

Source code:

self.ref?.child("data").child("success").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
   if snapshot != nil {
        // Your answer goes here
   }
}
like image 235
techcoderx Avatar asked Jul 16 '17 07:07

techcoderx


2 Answers

Snapshots have two properties.

snapshot.key
snapshot.value

When using an observer with .value. all of the key: value children are returned in the snapshot. They can be iterated over to capture each key: value pair like this.

ref.observeSingleEvent(of: .value, with: { (snapshot) in
    for child in snapshot.children {
        let snap = child as! DataSnapshot
        let key = snap.key
        let value = snap.value
        print("key = \(key)  value = \(value!)")
    }
})

Keep in mind that the value property could be a string, number, array or another dictionary (snapshot). In the original question it's a String.

like image 98
Jay Avatar answered Oct 09 '22 08:10

Jay


Something like this should work (with better named variables):

  1. Cast the snapshot.value as a dictionary
  2. Use the dictionary's .keys & .values properties to retrieve them as LazyMapCollection types.
  3. Initialise an array with the collections.

Code:

self.ref?
    .child("data")
    .child("success")
    .child(userID!)
    .observeSingleEvent(of: .value, with: { (snapshot) in
        if let data = snapshot.value as? [String: Any] {
            let keys = Array(data.keys)
            let values = Array(data.values)
            ... // Your code here
        }
    }

Update - To show example where order is respected:

I would probably save the dictionary to an array, which casts it to type Array<(key: String, value: Any)>. Then, you can map it to keys or values and keep the order.

... // As above
    .observeSingleEvent(of: .value, with: { (snapshot) in
        if let data = snapshot.value as? [String: Any] {
            let dataArray = Array(data)
            let keys = dataArray.map { $0.0 }
            let values = dataArray.map { $0.1 }
            ... // Your code here
        }
    }
like image 6
Yasir Avatar answered Oct 09 '22 08:10

Yasir