我有一个阻止时刻。在getDataByDate
case .success
中,我获得了一些数据。这是阵列。之后我需要将该数组推入callAnother
并使用循环中的数组元素。我推入myAnotherMethod
和completion
块中的每个元素我都想创建arrayForDataSourceSave
并将其发送到self?.dataSource.save(data: data, add: arrayForDataSourceSave
每次add
为空时。如何解决这个问题?
private func callAnother(data: [AnyModel], completion: @escaping () -> Void) {
var arrayForDataSourceSave: []()
for element in data {
guard let id = element.id else { return }
APIService.myAnotherMethod(id: id, completion: { result in
switch result {
case .success(let well):
arrayForDataSourceSave.append(well)
print(well)
case .error(let error):
print("request error: \(error)")
}
})
}
completion()
}
func refresh(completion: @escaping () -> Void) {
APIService.getDataByDate(date: date, completion: { [weak self] (result) in
switch result {
case .success(let data):
self?.callAnother(data: data, completion: {
self?.dataSource.save(data: data, add: arrayForDataSourceSave)
})
case .error(let error):
print("request error: \(error)")
}
completion()
})
}
答案 0 :(得分:0)
我用DispatchGroup
找到了该任务的决定,我的代码效果很好:
private func callAnother(data: [AnyModel]) {
let dispatchGroup = DispatchGroup()
var arrayForDataSourceSave = [AnyModel]()
for element in data {
guard let id = element.id else { return }
dispatchGroup.enter()
APIService.myAnotherMethod(id: id, completion: { result in
switch result {
case .success(let well):
arrayForDataSourceSave.append(well)
print(well)
case .error(let error):
print("request error: \(error)")
}
dispatchGroup.leave()
})
}
dispatchGroup.notify(queue: DispatchQueue.main) {
self?.dataSource.save(data: data, add: arrayForDataSourceSave)
}
}
func refresh(completion: @escaping () -> Void) {
APIService.getDataByDate(date: date, completion: { [weak self] (result) in
switch result {
case .success(let data):
self?.callAnother(data: data)
case .error(let error):
print("request error: \(error)")
}
completion()
})
}