一次循环执行一次异步方法,Swift 4

时间:2019-03-09 13:28:52

标签: swift grand-central-dispatch

在执行下一个(i + 1)之前,我需要performAsyncRequests方法(针对每个i)完成。我正在尝试:

let group = DispatchGroup()
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1

for i in 0..<results.count {
    group.enter()
    print("\(i)-async started")
    queue.addOperation {
        print("Operation \(i) added")
        self.performAsyncRequests(completion: { (result) in
            print("Request \(i) completed")
            group.leave()
        })
    }
}
group.notify(queue: .main) {
    print("All requests completed")
    self.reloadTableView()
}

但是这会同时执行几个请求。欣赏是否有人可以指出我正确的方向。

2 个答案:

答案 0 :(得分:0)

DispatchGroup是错误的API。我确保无论执行顺序如何,在上一次操作完成之前都不会调用notify闭包。

可能的解决方案是将asynchronous Operation与非并发队列一起使用。

答案 1 :(得分:0)

最简单的解决方案是编写一个递归执行请求的例程,例如:

func performNextRequest(_ index: Int = 0) {
    guard index < results.count else {
        DispatchQueue.main.async {
            // initiate whatever you want when this is done
            self.reloadTableView()
        }
        return
    }

    performAsyncRequest(index) { [weak self] in
        self?.performNextRequest(index + 1)
    }
}

更优雅的解决方案是使用一些异步模式,例如异步Operation子类或promises。