I\'m having issues in a query from swift to firebase. bellow is my sample JSON in firebase:
Lulibvi-d220
Contas
-KwlPQZTqVfNhHAsFyW5
Nome: \"Ass
tl;dr: To debug your asynchronous code in XCode, place a breakpoint on the first statement inside the completion handler.
Longer explanation:
When you observe a value from Firebase, it may take any amount of time to get that data. To prevent your program from being blocked during this time, the data is loaded from the Firebase database in the background while your code continues. Then when the data becomes available, Firebase calls your completion handler.
This pattern is known as asynchronous loading, and is common to pretty much any modern web API. But it can be incredibly hard to get used to.
One easy way to see what happens is to run the code with a few well-place logging statements:
ref = Database.database().reference()
print("Before attaching observer")
ref.child("Contas").child("Assets").observeSingleEvent(of: .value) { (snapshot) in
print("Inside completion handler")
}
print("After attaching observer")
This code will immediately print:
Before attaching observer
After attaching observer
And then after a few moments (depending on network speed and other factors):
Inside completion handler
While there are ways to make the code after the block wait for the data (see some of the links below for more on that), the more common way to deal with asynchronous loading is to reframe the question. Instead of trying to code "first get the data, then print it", frame your problem as "we start getting the data. whenever we get the data, we print it".
The way to model this into code is that you move all code that needs access to the data from Firebase into the completion handler of your observer. Your code already does that by having print (numero as Any)
in there.
To debug your asynchronous code in XCode, place a breakpoint on the code inside the completion handler. That breakpoint will then be hit when the data comes back from Firebase.
A few questions that also deal with this behavior: