Sudeep Swarnapuri
Sudeep Swarnapuri

Reputation: 41

How to save Firebase Data into an Array

I have a Firebase database that is modeled as such:

: users
    : some-random-id-1
        - username:"user1"
        - email:"[email protected]"
    : some-random-id-2
        - username:"user2"
        - email:"[email protected]"

I am trying to iterate through all the users in the dictionary of data and append the username into a list in the file to be used for other purposes. I created a string array (userslist) variable and in viewdidload(), I wrote the following code below:

    ref = Database.database().reference()
    ref?.observe(.value, with: { (snapshot) in
        let dataDict = snapshot.value as! NSDictionary
        let x = dataDict["users"] as! NSDictionary
        print(x)
        print("--------")
        for user in x{
            let y = user.value as? [String: String]
            let z = y!["username"]
            print(z)
            self.userslist.append(z!)
            print(self.userslist)
            print("NEXT")
        }
    })
    print(self.userslist)

Inside the brackets of the snapshot, when I print self.userslist, I can see that each element is getting added, but when I print it a final time outside of the brackets, it shows it as an empty array. I think that the elements are only appended in the scope of those brackets so I cant access the filled array anywhere else. How do I get around this so I can use the data I appended?

Upvotes: 2

Views: 656

Answers (1)

iOS Geek
iOS Geek

Reputation: 4855

you are using print(self.userslist) outside the observer and Firebase run in Async Mode

So, if you make use of breakpoints you will notice that

print(self.userslist) is Called before the control reach onside the Database handler ,

data is getting fetched you need to load your views inside that handler using Dispatch main queue

    ref?.observe(.value, with: { (snapshot) in
            let dataDict = snapshot.value as! NSDictionary
            let x = dataDict["users"] as! NSDictionary
            print(x)
            print("--------")
            for user in x{
                let y = user.value as? [String: String]
                let z = y!["username"]
                print(z)
                self.userslist.append(z!)
                print(self.userslist)
                print("NEXT")
            }
            /// Here is your data
            print(self.userslist)
        })
 /// Called before Handler execution
 print(self.userslist)

Upvotes: 1

Related Questions