Y.Şevli Y.Şevli - 3 months ago 19
Swift Question

Append Firebase data to an array in Swift ios

I don't know what I am doing wrong! I just simply want to take data from Firebase database and iterate for each result and put them into an array. I have tried serval different approaches. But they all return results adding one at a time to the array. I have data like below:

{
"1400001" : {
"HHtype" : 3,
"Sesgrup" : 4,
"lg_Et harcaması" : 0,
"lg_Total Harcama" : 3.11
},
"1400002" : {
"HHtype" : 1,
"Sesgrup" : 4,
"lg_Et harcaması" : 1.2,
"lg_Total Harcama" : 3.15
},
"1400004" : {
"HHtype" : 3,
"Sesgrup" : 4,
"lg_Et harcaması" : 1.18,
"lg_Total Harcama" : 3.06
},
"1400005" : {
"HHtype" : 4,
"Sesgrup" : 3,
"lg_Et harcaması" : 2.21,
"lg_Total Harcama" : 3.74
},
.......


And, I am using a code that is below :

func sen(){
var rootRef: FIRDatabaseReference!
var refHandle: UInt!
var haneRef: FIRDatabaseReference!
var numbersArray = [Int] ()



rootRef = FIRDatabase.database().reference()
haneRef = rootRef.child("SES2014")


haneRef.queryOrderedByChild("lg_Et harcaması").queryLimitedToLast(4).observeEventType(.ChildAdded, withBlock: { (snapshot) in
let hhtype = snapshot.value!["HHtype"] as? Int
numbersArray.append(hhtype!)
print(numbersArray)



})

}


And, the result is:

[3]
[3, 1]
[3, 1, 4]
[3, 1, 4, 4]


I want to get only the last array: [3, 1, 4, 4]

How can I do this ? Thanks

Answer
func sen(){
        var rootRef: FIRDatabaseReference!
        var refHandle: UInt!
        var haneRef: FIRDatabaseReference!
        var numbersArray = [Int] ()



        rootRef = FIRDatabase.database().reference()
        haneRef = rootRef.child("SES2014")

        let queryCount = 4
        haneRef.queryOrderedByChild("lg_Et harcaması").queryLimitedToLast(queryCount).observeEventType(.ChildAdded, withBlock: { (snapshot) in
            let hhtype = snapshot.value!["HHtype"] as? Int
            numbersArray.append(hhtype!)
            queryCount -= 1
            if queryCount <= 0 {
                print(numbersArray)
            }



        })

    }