Firebase DataDescription返回空数组

时间:2019-05-24 16:16:52

标签: swift firebase google-cloud-firestore

我正在尝试从1个文档中将所有字段都用作字典。但是当我尝试这样做时,我只会得到空数组返回。我尝试从文档中获取帮助,但无法正常工作。

这行代码表明它不为空

print(“缓存的文档数据:(dataDescription)”)

var user:String = (Auth.auth().currentUser?.email)! // I used email as name of document.

var Groups = [String:Any]()

    let docRef = AppDelegate.db.collection("JoinedGroups").document(user)

    docRef.getDocument(source: .cache) { (document, error) in
        if let document = document {
            let dataDescription = document.data()
            self.Groups = dataDescription!   // unwrapping here
            print("Cached document data: \(dataDescription)")
        } else {
            print("Document does not exist in cache")
        }
    }
    // Do any additional setup after loading the view.
    print(Groups)

}

这是我的结果: 当我将鼠标悬停在定义上时,document.data()显示为字典

[:] //显示为空?

缓存的文档数据:可选([[“ test new”:新测试,“ g3”:g3,“ g1”:g1])

非常感谢您能在此问题上获得一些帮助。

1 个答案:

答案 0 :(得分:1)

这里的主要问题是FireStore是异步的。 Firestore需要花费一些时间才能从互联网返回数据,并且该数据仅在getDocument之后的 内有效。

这意味着print(Groups)函数将在闭包内部的代码之前执行,因此为空。将打印件移到封盖内即可。

var Groups = [String:Any]()
    let docRef = AppDelegate.db.collection("JoinedGroups").document(user)
    docRef.getDocument(source: .cache) { (document, error) in
        if let document = document {
            let dataDescription = document.data()
            self.Groups = dataDescription!   // unwrapping here
            print("Cached document data: \(dataDescription)")
        } else {
            print("Document does not exist in cache")
        }
        print(self.Groups)
    } 
}

我还可以建议您使用var均为小写形式的命名约定,例如组而不是组。大写通常用于类定义UserClass或GroupClass。

最后一件事... documentID(其“键”)无法更改。这意味着如果您的结构是这样

JoinedGroups
   jimmy@email.com
      name: "Jimmy"
      fav_food: "Pizza"

并且您在整个应用程序中都引用了该用户,当他们决定更改其电子邮件提供商时,您将必须遍历结构中的所有位置,读入该节点,删除该节点,然后用更新后的电子邮件将其写回。解决方法是将documentID(密钥)与其包含的数据解除关联

JoinedGroups
   users_uid
      name: "Jimmy"
      fav_food: "Pizza"

由于uid永远不变,因此电子邮件可以更改20次,并且不会影响您的应用。