簡體   English   中英

如何獲取 Firestore 數據庫更改的通知並請求僅對更改的文檔(添加或更新)進行調用

[英]How to get notifications of Firestore Database changes & request a get call for only the changed documents (added or updated)

到目前為止,我可以將快照監聽器添加到集合中:

db.collection("products/country/class/grade1/test").order(by: "qId").addSnapshotListener { [self] (querySnapshot, error) in
            
            //Handle Error:
            if let error = error {
                
                print("Error getting documents: \(error.localizedDescription)")
                
            } else {
                
                //No Documents Found:
                guard let documents = querySnapshot?.documents else {
                    return
                }
                
                documents.compactMap { doc in
                    
                    let value = doc.data()
                    print (value)

               }
           }
}

但是,我希望它出現一個小徽章,表明有數據庫更改&當用戶按下更新按鈕時,它只加載更改(添加或更新)的文檔

class ChannelsViewController: UITableViewController { 
      private var channelReference: CollectionReference {
        return database.collection("channels")
      }
      private var channels: [Channel] = []
    override func viewDidLoad() {
    super.viewDidLoad()

      channelListener = channelReference.addSnapshotListener { [weak self] 
      querySnapshot, error in
      guard let self = self else { return }
      guard let snapshot = querySnapshot else {
        print("Error listening for channel updates: \. 
     (error?.localizedDescription ?? "No error")")
        return
       }

      snapshot.documentChanges.forEach { change in
        self.handleDocumentChange(change)
        }
      }
   }
      
   private func addChannelToTable(_ channel: Channel) {
       if channels.contains(channel) {
         return
        }

       channels.append(channel)
       channels.sort()

       guard let index = channels.firstIndex(of: channel) else {
         return
        }
        tableView.insertRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
     }

   private func updateChannelInTable(_ channel: Channel) {
      guard let index = channels.firstIndex(of: channel) else {
       return
      }

    channels[index] = channel
    tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
    }

   private func removeChannelFromTable(_ channel: Channel) {
      guard let index = channels.firstIndex(of: channel) else {
        return
      }

     channels.remove(at: index)
     tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
    }

  private func handleDocumentChange(_ change: DocumentChange) {
      guard let channel = Channel(document: change.document) else {
       return
     }

    switch change.type {
    case .added:
      addChannelToTable(channel)
    case .modified:
      updateChannelInTable(channel)
    case .removed:
      removeChannelFromTable(channel)
    }
  }


}

這是一個在集合名稱“channel”和 Channel 上添加、更新和刪除時自動更新 tableView 的示例:

import FirebaseFirestore

struct Channel {
  let id: String?
  let name: String

  init(name: String) {
    id = nil
    self.name = name
  }

  init?(document: QueryDocumentSnapshot) {
    let data = document.data()

    guard let name = data["name"] as? String else {
      return nil
    }

    id = document.documentID
    self.name = name
  }
}

// MARK: - DatabaseRepresentation
extension Channel: DatabaseRepresentation {
  var representation: [String: Any] {
    var rep = ["name": name]

    if let id = id {
      rep["id"] = id
    }

    return rep
  }
}

// MARK: - Comparable
extension Channel: Comparable {
  static func == (lhs: Channel, rhs: Channel) -> Bool {
    return lhs.id == rhs.id
  }

  static func < (lhs: Channel, rhs: Channel) -> Bool {
    return lhs.name < rhs.name
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM