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

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

问题描述

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

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)
        }

比我应该数数并显示出来.

Than I should count it and display.

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 Closure中的UI更新是在主线程上调用的.因此,例如,如果您在闭包内加载tableView dataSource,则也可以在闭包内调用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天全站免登陆