在onAppear中使用DispatchGroup

时间:2020-04-23 15:44:11

标签: swiftui cloudkit

我想要实现的是:
1)从cloudkit中获取记录(不包括资产)
2)从获取的记录中随机选择3个recordIDs
3)从cloudkit中获取全部3条记录(包括资产)。

我正在努力解决的问题是确保1,2,&3开始并一个接一个地完成。

    //...
    .onAppear(){

            let group = DispatchGroup()

            // MARK: - 1) fetch from CloudKit - excluding CKAsset
            CloudKit.fetch() {(result) in
                group.enter() // moving group.enter() above CloudKit.fetch() locks everything up
                switch result {
                case .success(let newItem):
                    self.array.append(newItem)
                    group.leave()
                case .failure(let err):
                    print(err.localizedDescription)
                }
            }
            // MARK: - 2) randomly select 3 records
            group.wait() // doesn't actually wait as this is executed before group.enter()
            self.array.shuffle()
            let firstSelection = self.array[0].recordID!
            let firstSelection = self.array[1].recordID!
            let firstSelection = self.array[2].recordID!

            // MARK: - 3) fetch recordID from CloudKit - includes CKAsset
            CloudKit.fetchRecord(recordID: self.array[0]) {(result) in
                switch result {
                case .success(let newItem):
                    self.arrayRandomlySelected.append(newItem)
                case .failure(let err):
                    print(err.localizedDescription)
                }
            }
            // run for remaining 2 records and move to next view when done
    }

我尝试使用DispatchGroup(),但在group.wait()之前调用了group.enter()。我是在正确使用DispatchGroup()还是应该尝试其他方法?

0 个答案:

没有答案