Firestore更新后仅提取一次文档 [英] Fetch document only once when Firestore has updated

查看:41
本文介绍了Firestore更新后仅提取一次文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个tableView可以从Firestore集合中获取所有文档,并且我希望在用户刷新tableView后将最后一个文档添加到Firestore中时仅获取最后一个文档一次,此后我要删除侦听器,以便在用户刷新时tableView仅一次获取文档,我使用了分离侦听器[从此处的文档] [1],但没有用

I have a tableView that bring all documents from Firestore collection and i want to fetch the last document only once when it is added to the Firestore after user refresh the tableView and after that I want to remove the listener so when the user refresh the tableView it only fetch document once , i used detach listener [from the documentation here][1] but it didn't work

func updatedFireStoredata() {
    
    
    let listener =  Firestore.firestore().collection("collection1").order(by: "date").limit(toLast: 1).addSnapshotListener() { querySnapshot, error in
        guard let snapshot = querySnapshot else {
            print("Error fetching snapshots: \(error!)")
            return
        }
        snapshot.documentChanges.forEach { diff in
            if (diff.type == .added) {
                
                let data = diff.document.data()
    
                self.amount.append(data["amount"] as? String ?? "")
                
                print("New city: \(diff.document.data())")
            }
            
        }
        
        
    }
    
    table2.reloadData()
    listener.remove()
}

推荐答案

如果您的目标是只调用一次以检索此文档,则可以考虑使用SDK内置的脱机持久性.您将需要在启用了离线持久性的情况下请求一次文档,但是在该调用之后,您可以从该本地缓存中请求此数据.

If your goal is to only call once to retrieve this document, I would consider using the offline persistence that is built in to the SDK. You will need to request the document once with offline persistence enabled, but after that call you can request this data from that local cache.

https://firebase.google.com/docs/firestore/manage-data/enable-offline https://firebase.google.com/docs/firestore/manage-data/enable-offline#disable_and_enable_network_access

或者,您可以将文档存储在本地,而不必将其包含在重新加载中.

Alternatively you could store the document locally, and not include it in reload.

如果确实是这种数据发生更改的情况(不是每次刷新都那么频繁),就可以将其移至事件模型.您可以使用firestore监视/监听来监视该查询并根据需要获取更新回调. https://firebase.google.com/docs/firestore/query-data/听

If it is the case that this data does change, just not as often as every refresh, it may make sense to move this to an eventing model. You can use firestore watch/listen to monitor that query and get update callbacks as needed. https://firebase.google.com/docs/firestore/query-data/listen

这篇关于Firestore更新后仅提取一次文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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