【发布时间】:2021-05-24 15:44:42
【问题描述】:
所以,在我的代码中,您可以看到我想返回从 Firebase 检索到的信息,但该方法总是返回一个空数组,我是 Swift 新手,您能解释一下为什么会这样吗?我怎样才能让它工作?非常感谢。
var catalog:[String:NSDictionary] = [String():NSDictionary()]
func readCatalogInfo()->[String:NSDictionary]{
let ref = Database.database(url: "https://reforestar-database-default-rtdb.europe-west1.firebasedatabase.app/").reference()
_ = ref.child("trees").observe(.value, with: {snapshot in
guard let information:[String:NSDictionary] = snapshot.value as? [String:NSDictionary] else {
print("Error in getting information about the Trees")
return
}
self.catalog = information
})
return self.catalog
}
【问题讨论】:
-
@vadian 提供了一个很好的答案,这可能是解决方案。请注意,有多种方法可以实现这一点,完成处理程序就是其中之一。如果您打算稍后使用数据,例如在目录中,那么将其填充到 Firebase 闭包中并且不尝试返回它也可以。例如;如果用户登录并在此后的某个时间点他们想要在其目录中查找零件。该目录可以在他们登录时预加载。我们不知道您的具体用例,因此请考虑如何使用该数据来确定解决方案。