ios - 如何在 Swift 中保存实时 Firebase 数据库中的数据?
问题描述
因此,在我的代码中,您可以看到我想返回从 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
}
解决方案
数据库请求异步工作,您必须添加一个完成处理程序。
并且不要NS...
在 Swift 中使用集合类型
var catalog = [String:[String:Any]]()
func readCatalogInfo(completion: @escaping ([String:[String:Any]]) -> Void) {
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 = snapshot.value as? [String:[String:Any]] else {
print("Error in getting information about the Trees")
return
}
completion(information)
})
}
并使用它
readCatalogInfo() { [weak self] result in
self?.catalog = result
}
推荐阅读
- python - 在 Kubernetes Python 客户端中使用 create_namespaced_secret API
- .net-core - NUnit、Serilog 和 Datadog
- angular - 如何编写像material.angular.io这样的sidenav
- c# - 模拟动作委托属性
- ag-grid - 无法更改行高
- python - 我不明白安装了什么版本的 CUDA。`nvidia-smi` 和 `nvcc` 命令返回不兼容的信息
- excel - 当按下 F9 并有一个按钮来计算这两张纸时,如何从计算中排除两张纸?
- python - 如何在 Python 中使用 Pillow 库向 PNG 图像添加轮廓/描边/边框?
- python - 是否有任何快速公式可以找到由 N 个点给出的一般四边形(六面体)的最大面积?
- css - mdc-select 呈现在一切之上