0

Hello I have a Firebase app and I would like to download all my database when the app launches. All this is working fine but I would like to know when the download completed.

    func getAllDevices(completion: @escaping (Bool) -> Void) {
    reference.child("devices").queryOrderedByKey().observe(.childAdded) { (snapshot) in
        if let data = snapshot.value as? [String: Any] {
            self.sync(device: data)
        }
       // completion(true)

    }

I tried with completion handler but it is not good because it gets called every time a new object is downloaded. Is there any way to get notified when it finished downloading?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Hunor Gocz
  • 137
  • 12
  • To detect when all initial children have been read, you'll need to observe the `.value` event. Here's one [example for Swift](https://stackoverflow.com/questions/46017039/firebase-childadded-and-activity-indicator/46018057#46018057) and for JavaScript (where the same logic applies): [1](https://stackoverflow.com/questions/19883736/how-to-discard-initial-data-in-a-firebase-db), [2](https://stackoverflow.com/questions/12850789/is-there-a-way-to-know-in-what-context-child-added-is-called-particularly-page/12851236#12851236), [3](https://stackoverflow.com/a/11618929). – Frank van Puffelen Oct 16 '17 at 14:36
  • Thank you for your help. I could solve the problem thanks to you:). – Hunor Gocz Oct 17 '17 at 06:04

1 Answers1

1

I could solve the problem using .value event. I did something like this and it is working fine now.

    func getAllDevices(completion: @escaping (Bool) -> Void) {
    reference.child("devices").queryOrderedByKey().observeSingleEvent(of: .value) { (snapshot) in

        if let devices = snapshot.value as? [String: Any] {
            for data in devices.values {
                self.sync(device: data as! [String : Any])
            }
        }

        completion(true)
    }
Hunor Gocz
  • 137
  • 12