在iOS上使用Swift多次调用Firebase'Observe' [英] Firebase 'Observe' called multiple times with Swift on iOS

查看:55
本文介绍了在iOS上使用Swift多次调用Firebase'Observe'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Firebase数据库节点上启动 observer 时,我注意到即使没有数据更改,Firebase仍会继续调用方法 observer .

When I start the observer on a Firebase database node, I notice that Firebase continues to call the method observer even when there is no data change.

这是我的设置:

FIRDatabase
    .database()
    .reference(withPath: "test")
    .observe(FIRDataEventType.value, with: { (snapshot) in
            print("Firebase Data Updated");
    }
);

当我对Firebase数据库进行一个更改时, observer 会多次调用其关闭函数.

When I make one change to the Firebase database, the observer calls its closure function more than one time.

Firebase数据已更新

Firebase Data Updated

Firebase数据已更新

Firebase Data Updated

Firebase数据已更新

Firebase Data Updated

Firebase数据已更新

Firebase Data Updated

Firebase数据已更新

Firebase Data Updated

Firebase数据已更新

Firebase Data Updated

Firebase数据已更新

Firebase Data Updated

...

为什么会这样?我如何才能阻止这种情况的发生,并且在更新后仅接到 observer 的一个电话?

Why does this occur? How can I stop this from occurring and get only one call to the observer after an update?

推荐答案

该观察者可能已被多次注册.当用户注销时,您注册的侦听器块保持注册状态,这样,当用户再次登录时,您正在注册第二个侦听器.

It's likely this observer is being registered multiple times. When the user logs out, the listener block that you registered stays registered, such that when the user logs in again, you are registering a second listener.

通常最好的做法是捕获观察者的 ref handle ,并在完成使用后将其删除(例如,当用户注销时).您可以这样做:

It is often good practice to capture the ref and handle of observers, and remove the handles once you're done with them (i.e. when a user logs out). You can do so as such:

ref, handle = FIRDatabase
    .database()
    .reference(withPath: "test")
    .observe(FIRDataEventType.value, with: { (snapshot) in
            print("Firebase Data Updated");
    }
);

退出时:

ref.removeObserverWithHandle(handle)

否则,确保只调用一次的另一种可能的解决方案是使用 .observeSingleEvent()而不是 .observe().

Otherwise another possible solution to ensure it is only called once is to use .observeSingleEvent() instead of .observe().

这篇关于在iOS上使用Swift多次调用Firebase'Observe'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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