如何从一个闭包到另一个闭包获得实际数据?

时间:2017-12-08 08:28:15

标签: ios swift closures

我有一个阻止时刻。在getDataByDate case .success中,我获得了一些数据。这是阵列。之后我需要将该数组推入callAnother并使用循环中的数组元素。我推入myAnotherMethodcompletion块中的每个元素我都想创建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()
    })
}

1 个答案:

答案 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()
    })
}