如何在firestore中添加或激活一次性侦听器

时间:2018-04-16 20:00:00

标签: swift google-cloud-firestore

我想在firestore中为文档更改添加一个监听器。不知何故,侦听器被多次触发,但我只想运行一次由侦听器触发的代码。基本上我想在触发一次后删除监听器。我怎样才能做到这一点?感谢

更新: 这是我想要使用的代码:

db.collection("cities").document("SF")
 .addSnapshotListener { documentSnapshot, error in
   guard let document = documentSnapshot else {
     print("Error fetching document: \(error!)")
     return
   }
   print("Current data: \(document.data())")
   //my other code
 }

可能会多次触发侦听器。我只希望“我的其他代码”执行一次,即第一次触发监听器。

2 个答案:

答案 0 :(得分:0)

我认为你正在寻找这样的东西:

let count = 0
let registration = db.collection("cities").document("SF")
 .addSnapshotListener { documentSnapshot, error in
   count = count + 1
   if count == 2 registration.remove()
   guard let document = documentSnapshot else {
     print("Error fetching document: \(error!)")
     return
   }
   print("Current data: \(document.data())")
   //my other code
 }

答案 1 :(得分:0)

以下是监听文档更改的代码。

/// Add listener to query
listener = db.collection("cities").document("SF").addSnapshotListener { (querySnapshot, error) in
     /// Check if snapshot is not nil
      guard let snapshot = querySnapshot else {
           print("Error: \(error.debugDescription)")
           return
      }

      /// Check if snapshot has documents and not empty
      guard snapshot.documents.last != nil else {
           // The collection is empty.
           return
      }

      /// This is the on change listner  
      snapshot.documentChanges.forEach({ (diff) in
           print(diff.document.data())
           if (diff.type == .added) {

           }
           else if (diff.type == .modified) {

           }
           else if (diff.type == .removed) {

           }
      })
}

现在您拥有listener的实例,您可以随时停止收听。

listener.remove()

BTW一次性使用时,您应该使用getDocuments(completion:)来调用一次。

编辑:getDocuments(completion:)示例

queryRef.whereField(key, isEqualTo: value).getDocuments(completion: { (querySnapshot, error) in
    if let _error = error {
        print (_error.localizedDescription)
        return;
    }

    guard let _querySnapshot = querySnapshot else {
          print("querySnapshot is nil")
          return;
    }

    for document in _querySnapshot.documents {
        print(document.data())
    }
})