如何更快地显示来自 Firebase 的数据? [英] How to display data from Firebase faster?

查看:26
本文介绍了如何更快地显示来自 Firebase 的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有来自 Firebase 的标签和数据.我需要获取数据,对其进行计数并更新标签.但我有问题.我得到数据的时间晚于开始计数.

I have label and data from Firebase. I need to get the data, count it and update Label. But I have problem. I get the data later than I start counting it.

 let uid = Auth.auth().currentUser?.uid
        let ref = Database.database().reference()
        ref.child("users").child(uid!).child("weight").observe(.value) { (snapshot) in
            self.userWeight = snapshot.value as! Float
            print(self.userWeight)
        }

我应该计算并显示.

self.maxAmountOfWater = (self.userWeight * 4) / 100
maxWaterLabel.text = String(maxAmountOfWater)

Label 的值为 0,因为我获取数据很慢.我在 viewDidLoad

Value of Label is 0 because I fetch data slow. I do it all in viewDidLoad

推荐答案

数据是从 Firebase 异步加载的,因为从服务器/网络下载下来可能需要一些时间.在加载数据时,您的主应用程序代码会继续运行.然后,一旦数据可用,就会调用您的完成处理程序.

Data is loaded from Firebase asynchronously, since it may take some time to come down from the server/network. Your main application code continues to run while the data is being loaded. Then once the data is available, your completion handler is called.

出于这个原因,任何需要来自数据库的数据的代码都必须在完成处理程序中,或者从那里调用.将它放在其他任何地方会导致不确定数据是否会在代码需要时加载.

For this reason, any code that requires data from the database, must be inside the completion handler, or called from there. Putting it anywhere else makes it uncertain that the data will have loaded by the time the code needs it.

例如:

let uid = Auth.auth().currentUser?.uid
let ref = Database.database().reference()
ref.child("users").child(uid!).child("weight").observe(.value) { (snapshot) in
    self.userWeight = snapshot.value as! Float
    print(self.userWeight)

    self.maxAmountOfWater = (self.userWeight * 4) / 100
    maxWaterLabel.text = String(maxAmountOfWater)
}

self.userWeight 的使用不在回调中,因此它可以在加载后立即访问数据库中的值.

Not the use of self.userWeight is inside the callback, so it has access to the value from the database as soon as it's loaded.

如果您愿意,还可以定义自己的完成处理程序,然后从 Firebase 完成处理程序中调用该处理程序,或使用调度组.有关这方面的一些示例,请参阅:

If you want you can also define your own completion handler, that you then call from within the Firebase completion handler, or use a dispatch group. For some examples of this, see:

请注意,Firebase 闭包中的 UI 更新是在主线程上调用的.因此,例如,如果您在闭包中加载 tableView 数据源,您也可以在闭包中调用 tableView.reloadData(),而无需使用调度组或其他线程.

Just a note that UI updates within a Firebase Closure are called on the main thread. So for example, if you load a tableView dataSource within the closure, you can call tableView.reloadData() within the closure as well without having to use a dispatch group or other thread.

这篇关于如何更快地显示来自 Firebase 的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆