如何执行一个接一个完成的多个Alamofire请求?

时间:2016-10-07 14:36:52

标签: swift alamofire nsoperationqueue

我想执行多个Alamofire请求。但是,由于数据依赖性,新请求应该仅在前一个请求完成时开始。

我已经向question提出了一个使用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
    }
}

为了确保在下一个请求开始之前完成请求,我使用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)
}

然而,输出是:

Operation #0 finished
Operation #3 finished
Operation #2 finished
Operation #1 finished

显然不正确。

如何通过Alamofire实现这一目标?

1 个答案:

答案 0 :(得分:3)

问题与您提出的related question中的问题相同:操作依赖关系是完成操作,如文档所述,但是您已经编写了代码,其中操作在异步调度将来执行的请求后退出(您创建并添加到队列的操作将按其依赖项设置的顺序完成,但请求将由NSURLSession底层Alamofire同时触发。

如果您需要串行执行,您可以执行以下操作:

// 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)
}

讨论了各种其他解决方案in connection to this question,可以说是重复的。还有Alamofire-Synchronous