Otheprogrammer
Otheprogrammer

Reputation: 155

value not appearing in the rest of my code

I'm populating my "filteredLocations" array by using this:

    let sampleRef = FIRDatabase.database().reference().child("SamplePost").child("post")

    sampleRef.observeSingleEvent(of:.value, with: {(snapshot) in
        if  let result = snapshot.children.allObjects as? [FIRDataSnapshot] {
            for child in result{
                let dictionary = child.value as? [String: AnyObject]
                let lat = dictionary?["lat"] as! Double
                let long = dictionary?["long"] as! Double
                let structure = MapPoints(Latitude: lat, Longitude: long)
                self.filteredLocations.append(structure)
                print("This is the amount in here \(self.filteredLocations.count)")

            }
        }
    })

the print statement within the my snapshot returns 2, but when I print filteredLocations.count anywhere else it returns 0. I have the Firebase code at the start of the viewdidload

Upvotes: 0

Views: 37

Answers (1)

Vlad
Vlad

Reputation: 1041

Your problem is that "sampleRef.observeSingleEvent" is asynchronous. What this means is that it is run in a background thread waiting for data while the app continues executing functions like viewWillAppear etc on the main thread.

By the time you get data back from the server the other print count methods would have already been executed before the array was populated with data.

To get a better understanding of this. Place a UIButton on your controller and bind it to a function that prints the array count. Then start the app and press the button. It should print 2 as by the time you press the button you should have got data back from the server.

Upvotes: 2

Related Questions