adding data and querying from swift to firebase

前端 未结 1 1282
野的像风
野的像风 2021-01-26 08:31

I\'m having issues in a query from swift to firebase. bellow is my sample JSON in firebase:

Lulibvi-d220

Contas

  -KwlPQZTqVfNhHAsFyW5
      Nome: \"Ass         


        
相关标签:
1条回答
  • 2021-01-26 08:50

    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:

    • Swift: Wait for Firebase to load before return a function
    • How to make app wait until Firebase request is finished
    • Finish asynchronous task in Firebase with Swift
    • How to execute code directly after Firebase finishes downloading?
    • Is there a way to wait for a query to be finished in Firebase?
    0 讨论(0)
提交回复
热议问题