更新时间:2023-01-03 16:39:30
问题与您提出的相关问题:如文档所述,操作依赖项是对操作的完成,但是您已经编写了代码,其中该操作在异步调度将来执行的请求后退出操作(您创建并添加到的操作队列将按照其依赖关系设置的顺序完成,但请求将由Alamofire底层的NSURLSession并发触发。
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)
}
讨论了各种其他解决方案 ,可以说是重复的。还有 Alamofire-Synchronous 。
Various other solutions are discussed in connection to this question, arguably a duplicate. There's also Alamofire-Synchronous.