【问题标题】:Get all documents at once in a completion handler with getDocuments in Firestore使用 Firestore 中的 getDocuments 在完成处理程序中一次获取所有文档
【发布时间】:2020-02-08 09:43:34
【问题描述】:

现在,我的代码将异步获取数据并将其附加到字典(我的 UserModel)

用户API:

// Get all Users
func allUser (completion: @escaping (UserModel) -> Void) {

    let db = Firestore.firestore()
    let docRef = db.collection("users")
    docRef.getDocuments { (querySnapshot, err) in
        for document in querySnapshot!.documents {
            let dic = document.data()
            let user = UserModel(dictionary: dic)
            completion(user)
        }
    }
}

在我的 ViewController 中:

UserApi.shared.allUser { (user) in
        self.users.append(user)
        self.tableViewUsers.reloadData()
    }

我正在尝试改变我的方法,并希望加载我字典中的所有数据。我用 DispatchGroup 尝试了这个(我没有使用 DispatchGroups 的经验,但用谷歌搜索):

UserAPI:与调度组一起尝试

// Get all Users
func allUser (completion: @escaping ([UserModel]) -> Void) {

    let dispatchGroup = DispatchGroup()
    var model = [UserModel]()

    let db = Firestore.firestore()
    let docRef = db.collection("users")
    docRef.getDocuments { (querySnapshot, err) in

        for document in querySnapshot!.documents {
            dispatchGroup.enter()
            print("disp enter")
            let dic = document.data()
            model.append(UserModel(dictionary: dic))
            dispatchGroup.leave()
            print("disp leave")
        }
    }
    dispatchGroup.notify(queue: .main) {
        completion(model)
        print("completion")
    }
}

使用此代码,首先调用完成处理程序,这显然不是我想要的。

我需要解决什么问题才能一次加载所有数据?

【问题讨论】:

    标签: swift google-cloud-firestore


    【解决方案1】:

    每个异步操作只需要进出调度组一次。由于(据我所知)您只有一个 getDocuments 呼叫,因此您应该只呼叫 enterleave 一次。

    比如:

    let dispatchGroup = DispatchGroup()
    var model = [UserModel]()
    
    let db = Firestore.firestore()
    let docRef = db.collection("users")
    dispatchGroup.enter()
    docRef.getDocuments { (querySnapshot, err) in
    
        for document in querySnapshot!.documents {
            let dic = document.data()
            model.append(UserModel(dictionary: dic))
        }
        dispatchGroup.leave()
    }
    ...
    

    【讨论】:

    • 啊……我也试过了,但是在我的 getDocuments 之后让 DG 离开了。谢谢!
    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2019-02-05
    相关资源
    最近更新 更多