我需要按顺序执行请求,尽管这不能使用Alamofire.
我想按顺序打印1到30(假设响应只是参数的回显)
// Only 1 connection per Host
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPMaximumConnectionsPerHost = 1
configuration.timeoutIntervalForRequest = 30
self.manager = Alamofire.Manager(configuration: configuration)
for i in 1...30 {
manager.request(.GET, "http://httpbin.org/get", "i" : i], encoding: .JSON)
.responseJSON { response in
switch (response.result){
case .Failure(let error):
print("error")
break;
case .Success(let json):
print(json)
}
})
Run Code Online (Sandbox Code Playgroud)
根据NSURLSessionConfiguration文件:
此属性确定基于此配置的会话中的任务对每个主机进行的最大同时连接数.
此限制是每个会话,因此如果您使用多个会话,您的应用程序整体可能会超出此限制.此外,根据您与Internet的连接,会话可能会使用低于您指定的下限.
OS X中的默认值为6,iOS中的默认值为4.
如您所见,此设置仅控制网络级别的连接数.一旦您使用NSURLSessionAlamofire作为基础的许多请求排队,由该类决定何时发出请求.使用NSURLSession或Alamofire无法保证请求的顺序,而无需以这种方式对其进行显式编码.
也就是说,通过将请求包装在NSOperations中,您可以获得所需的行为.如果你创建NSOperationQueue了.maxConcurrentOperationCount的1,其本质就是一个串行队列.然后使用您已编写的相同循环,您应该能够像这样包装您的Alamofire请求:
queue.addOperationWithBlock {
manager.request(.GET, "http://httpbin.org/get", "i" : i], encoding: .JSON)
.responseJSON { response in
switch (response.result){
case .Failure(let error):
print("error")
break;
case .Success(let json):
print(json)
}
})
}
Run Code Online (Sandbox Code Playgroud)
随着.maxConcurrentOperationCount中1,队列顺序应该采取行动,正如我所说.因此,根据NSOperationQueue文档,您的操作将按照添加到队列的顺序执行.所以你应该看到你想要的1到30的结果.
所有这些都说,对于你想要解决的问题,可能有更好的解决方案,除非这只是一个编码工作,以使这些结果有序.
| 归档时间: |
|
| 查看次数: |
4693 次 |
| 最近记录: |