正确使用Firestore差异的方法

时间:2018-07-10 02:33:34

标签: ios swift firebase google-cloud-firestore

我正在调用此函数以从Firestore检索用户: 每次修改用户时,我都要更新users数组。

curl 127.0.0.1:8080/function/license -H 'Content-Type: application/json' --data-binary '{"hosts":["YYYXXXAAABBBCCC"]}'

但是,如果只有一个用户被修改并且我的collectionview重新加载,然后仅显示一个用户,则我的数组始终返回1!我如何 返回所有用户,即使只有一个被修改? 谢谢

新功能:

func fetchUsers( complete: @escaping ( _ success: Bool, _ users: [User], _ error: Error? )->()) {
    //self.users = []
    let circleId  = UserDefaults.standard.string(forKey: "circleId") ?? ""
    DataService.call.REF_CIRCLES.document(circleId).collection("insiders").order(by: "position", descending: false).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()
                let id = diff.document.documentID
                let user = User(key: id, data: data)
                self.users.append(user)
                complete(true, self.users, nil)
            }

            if (diff.type == .modified) {
                // Update users array if user data is modified
                if !self.users.isEmpty {
                    self.users = []
                let data = diff.document.data()
                let id = diff.document.documentID
                let user = User(key: id, data: data)
                self.users.append(user)
                complete(true, self.users, nil)
                }
            }

            if (diff.type == .removed) {
                print("Removed user: \(diff.document.data())")
            }
        }
    }
}

现在我在collectionview中看到很多重复的用户

1 个答案:

答案 0 :(得分:1)

您正在遍历QuerySnapshot.documentChanges,其中仅包含自上次快照以来已更改的文档。

要获取查询中的所有文档(而不仅仅是修改后的文档),请遍历QuerySnapshot.documents

DataService.call.REF_CIRCLES.document(circleId).collection("insiders").order(by: "position", descending: false).addSnapshotListener { querySnapshot, error in
    guard let snapshot = querySnapshot else {
        print("Error fetching snapshots: \(error!)")
        return
    }

    snapshot.documents.forEach { diff in
      ...