How is it possible to perform multiple Alamofire requests that are finished one after another?

不羁的心 提交于 2019-12-02 08:47:49
mz2

The issue is just the same as in the related question you posed: the operation dependencies are on finishing an operation, as documented, but you have written code where the operation exits after asynchronously dispatching a request for future execution (the operations you created and added to a queue will finish in the order set by their dependencies, but the requests will be fired concurrently by the NSURLSession underlying Alamofire).

If you need serial execution, you can for instance do the following:

// you should create an operation queue, not use OperationQueue.main here –
// synchronous network IO that would end up waiting on main queue is a real bad idea.
let operationQueue = OperationQueue()
let timeout:TimeInterval = 30.0

for operationNumber in 0..<4 {
    let operation = BlockOperation {
        let s = DispatchSemaphore(value: 0)
        self.performAlamofireRequest(operationNumber) { number in
            // do stuff with the response.
            s.signal()
        }

        // the timeout here is really an extra safety measure – the request itself should time out and end up firing the completion handler.
        s.wait(timeout: DispatchTime(DispatchTime.now, Int64(timeout * Double(NSEC_PER_SEC))))
    }

    operationQueue.addOperation(operation)
}

Various other solutions are discussed in connection to this question, arguably a duplicate. There's also Alamofire-Synchronous.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!