Why I couldn't assign fetched values from Firestore to an array in Swift?

前端 未结 1 578
梦谈多话
梦谈多话 2020-12-22 13:32

I tried several times with various ways to assign the collected values of documents from firestore into an array. Unfortunately, I could\'t find a way to solve this issue.

相关标签:
1条回答
  • 2020-12-22 14:04

    That's actually the expected result, since data is loaded from Firestore asynchronously.

    Once you call getDocuments(), the Firestore client goes of and connects to the server to read those documents. Since that may take quite some time, it allows your application to continue running in the meantime. Then when the documents are available, it calls your closure. But that means the documents are only available after the closure has been called.

    It's easiest to understand this flow, by placing a few print statements:

    print("Before starting to get documents");
    db.collection("Hotels").getDocuments() { (querySnapshot,  err) in
      print("Got documents");
    }
    print("After starting to get documents");
    

    When you run this code, it will print:

    Before starting to get documents

    After starting to get documents

    Got documents

    Now when you first saw this code, that is probably not the output your expected. But it completely explains why the print(self.hotelCities) you have after the closure doesn't print anything: the data hasn't been loaded yet.

    The quick solution is to make sure that all code that needs the documents is inside of the close that is called when the documents are loaded. Just like your top print(self.hotelCities) statement already is.

    An alternative is to define your own closure as shown in this answer: https://stackoverflow.com/a/38364861

    0 讨论(0)
提交回复
热议问题