-3

I am trying to write a function to get data from firebase and update a global variable (branch), I understand that the background thread responsible for that so the main thread can continue even-though the background thread haven't finished yet, but I don't want that. How can I force the main thread to wait until the global variable is updated?

Here is the function:

func getID(email: String){
    databaseRef = Database.database().reference()
    databaseRef.root.child("Branches").observe(.value, with: { (snapshot) in
        if ((snapshot.children.allObjects as? [DataSnapshot]) != nil) {
            let child = snapshot.value as! [String: [String : String]]
            for (key, data) in child{
                for (k, d) in data{
                    if k == "Email" && d == email {
                        self.branch = key
                    }
                }
            }
        }
    })
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Mor Goren
  • 105
  • 9
  • 5
    It is not a good practice to hold main thread for a background task. You can use escape closures for notifying after the background task is completed. – Vaisakh KP Feb 28 '19 at 11:38
  • 1
    See https://stackoverflow.com/q/54322884, https://stackoverflow.com/a/49579711, https://stackoverflow.com/q/41628089, [more from these](https://stackoverflow.com/search?q=%5Bfirebase-realtime-database%5D%5Bswift%5D+asynchronous+wait) and https://stackoverflow.com/a/27345823. The last one of this shows how to accomplish what you ask, but as others have already commented and answered, you're much better off learning how to deal with the asynchronous behavior as this is incredibly common when using modern cloud-based APIs. – Frank van Puffelen Feb 28 '19 at 14:29
  • 1
    I'm with @FrankvanPuffelen here. But, the function showing in your question could happen in less than a second... or maybe not. I suspect you are looking for something in your data - perhaps a query would be a better solution than a loop as that will return a specific piece(s) of data. What's the use case? – Jay Feb 28 '19 at 19:31

1 Answers1

0

I assume we are talking about iOS, so: Being unresponse is about the worst you can do to the so-called "user experience" - and waiting for some network resources is definetly unpredictable. If you block the main thread too long (say: 30 seconds), the iOS operation system will kill your app. Before that, the user typically will exit your app and never start it again but and remove it from the device.

I would recomment to use a progress indicator and a informative message instead, and just dim (disable etc.) all the user controls, while the app is waiting for data. Maybe even with a cancel button.

Andreas Oetjen
  • 9,889
  • 1
  • 24
  • 34