如何构造代码以处理异步Firebase快照? [英] How to structure code to deal with asynchronous Firebase snapshot?
问题描述
我有一个无法解决的问题.JS中有很多问题,但我不太了解.
I have an problem that I can not solve. A lot of questions are in JS and I don't really understand them.
我将Firebase用作我的IOS应用程序和Swift的数据库.这是我的情况:
I'm using Firebase as my database for my IOS app and Swift. Here is my situation:
我有一个类文件,其中包含可以检索数据库中值的函数.我在某些 viewControllers
中调用这些函数.
I have a class file that contains functions that can retrieve values in my database. I'm calling these functions in some viewControllers
.
这些函数检索的值将立即在这些 viewControllers
中使用.
The values retrieved by these functions are immediately used in these viewControllers
.
我的问题是我的应用程序由于类文件函数返回的nil值而崩溃.发生这种情况是由于异步Firebase快照.
My problem is that my app crash because of nil values returned by the class file functions. This happen because of the asynchronous Firebase snapshot.
假定包含值的变量在分配值之前已使用=>我的应用程序崩溃,或打印的值为nil.
The variables assumed to contain the values are used before their value is assigned => My app crash, or printed values are nil.
然后我的问题很简单:如何构建代码以避免出现此问题?我已经尝试完成了,但这对我不起作用:函数仍然是异步的.
Then my question is simple: How can I structure my code to avoid this issue? I already tried completions, but that's not working for me: functions are still asynchronous.
这是我在类文件中的功能之一:
func initAverageMark(completionHandler: @escaping (_ mark: Double) -> ()) {
let userRef = ref.child("users").child((user?.uid)!).child("mark")
userRef.observeSingleEvent(of: .value, with: { (snapshot) -> Void in
if let mark: Double = snapshot.value as? Double {
completionHandler(mark)
}
}) { (error) in
print(error.localizedDescription)
}
}
我的其中一个viewController代码:
private var totalAsks: Double!
override func viewDidLoad() {
super.viewDidLoad()
initInfos()
}
func initInfos() {
mainUser().initTotalAsks{ total in
self.totalAsks = total
}
initLabels()
}
func initLabels() {
totalAsksLabel.text = " \(totalAsks!)" // it crashs here
}
推荐答案
假定您要在viewController中将某些标签或某些内容设置为mark的值,就可以这样做.
Assuming you'd want to set some label or something in your viewController to the value of mark you'd do it like this.
mainUser().initTotalAsks { mark in
self.totalAsksLabel.text = " \(mark)"
}
编辑
或者,如果您绝对要使用该Double.
Edit
Or if you absolutely want to use that Double.
private var totalAsks: Double? = nil {
didSet {
initLabels()
}
}
override func viewDidLoad() {
super.viewDidLoad()
initInfos()
}
func initInfos() {
mainUser().initTotalAsks{ total in
self.totalAsks = total
}
}
func initLabels() {
guard totalAsks != nil else {
return
}
totalAsksLabel.text = " \(totalAsks!)"
}
这篇关于如何构造代码以处理异步Firebase快照?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!