为什么我无法从Firestore中将获取的值分配给Swift中的数组?

时间:2018-09-09 13:19:09

标签: ios swift xcode firebase google-cloud-firestore

我尝试了多种方法,将来自Firestore的文档收集值分配给一个数组。不幸的是,我找不到解决此问题的方法。我附上了我最近尝试实现的代码。在Firestore关闭之前,它包含一个打印语句,该语句可成功打印所有获取的值。但是,在关闭之后,我尝试打印相同的数组,结果是一个空数组。

我尝试实现此代码

var hotelCities: [String] = []

func getCities() {
    db.collection("Hotels").getDocuments() { (querySnapshot,  err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                var found = false
                let documentDetails = document.data() as NSDictionary
                let location = documentDetails["Location"] as! NSDictionary
                let city = location["city"]!
                if (self.hotelCities.count == 0) {
                    self.hotelCities.append(String(describing: city))
                }
                else{
                    for item in self.hotelCities {
                        if item == String(describing: city){
                            found = true
                        }
                    }
                    if (found == false){
                        self.hotelCities.append(String(describing: city))
                    }
                }
            }
        }
        print(self.hotelCities)
    }
    print(self.hotelCities)
}

1 个答案:

答案 0 :(得分:0)

这实际上是预期的结果,因为数据是从Firestore异步加载的。

一旦您致电getDocuments(),Firestore客户端就会离开并连接到服务器以读取这些文档。由于那可能要花费一些时间,因此它可以让您的应用程序同时继续运行。然后,当文档可用时,它将调用您的关闭。但这意味着文档仅在调用闭包之后才可用。

通过放置一些打印语句,最容易理解此流程:

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

运行此代码时,它将打印:

  

开始获取文档之前

     

开始获取文件后

     

获得的文件

现在,当您第一次看到此代码时,可能不是您期望的输出。但这完全解释了为什么关闭后的print(self.hotelCities)无法打印任何内容:尚未加载数据。

快速的解决方案是确保需要文档的所有代码都在装入文档时调用的关闭内。就像您最重要的print(self.hotelCities)声明一样。

另一种方法是定义自己的闭包,如以下答案所示:System.Drawing.Font