Tac*_*aco 1 nsoperationqueue swift alamofire
我想执行多个 Alamofire 请求。但是,由于数据依赖性,新请求应仅在前一个请求完成时开始。
我已经用更一般的异步请求示例提出了一个问题,该示例使用OperationQueue. 但是,我没有成功地使用 Alamofire 实现相同的目标。
public func performAlamofireRequest(_ number: Int, success: @escaping (Int) -> Void)->Void {
Alamofire.request(String(format: "http://jsonplaceholder.typicode.com/posts/%i", number+1)) // NSURLSession dispatch queue
.responseString { response in // Completion handler at main dispatch queue?
if response.result.isSuccess {
// print("data")
} else if response.result.isFailure {
// print("error")
}
success(number) // Always leave closure in this example
}
}
Run Code Online (Sandbox Code Playgroud)
为了确保在下一个请求开始之前完成请求,我使用OperationQueue如下:
let operationQueue = OperationQueue.main
for operationNumber in 0..<4 { // Create some operations
let operation = BlockOperation(block: {
performAlamofireRequest(operationNumber) { number in
print("Operation #\(number) finished")
}
})
operation.name = "Operation #\(operationNumber)"
if operationNumber > 0 {
operation.addDependency(operationQueue.operations.last!)
}
operationQueue.addOperation(operation)
}
Run Code Online (Sandbox Code Playgroud)
但是,输出是:
Operation #0 finished
Operation #3 finished
Operation #2 finished
Operation #1 finished
Run Code Online (Sandbox Code Playgroud)
这显然是不正确的。
如何使用 Alamofire 实现这一目标?
该问题与您提出的相关问题相同:操作依赖于完成操作,如文档所示,但是您编写了代码,在异步调度未来执行请求(您创建和添加的操作)后,操作退出到队列将按照其依赖项设置的顺序完成,但请求将由 Alamofire 底层的 NSURLSession 并发触发)。
如果您需要串行执行,您可以例如执行以下操作:
// 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)
}
Run Code Online (Sandbox Code Playgroud)
与此问题相关的各种其他解决方案被讨论,可以说是重复的。还有Alamofire-Synchronous。
| 归档时间: |
|
| 查看次数: |
1943 次 |
| 最近记录: |