ios - Alamofire 串行请求

标签 ios alamofire

我需要按顺序执行请求,尽管这在使用 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)
            }
     })

最佳答案

根据 NSURLSessionConfiguration 的文档:

This property determines the maximum number of simultaneous connections made to each host by tasks within sessions based on this configuration.

This limit is per session, so if you use multiple sessions, your app as a whole may exceed this limit. Additionally, depending on your connection to the Internet, a session may use a lower limit than the one you specify.

The default value is 6 in OS X, or 4 in iOS.

如您所见,此设置仅控制网络级别的连接数。使用作为 Alamofire 基础的 NSURLSession 对多个请求进行排队后,由该类确定何时发出请求。使用 NSURLSession 或 Alamofire 无法保证在不以这种方式显式编码的情况下发出请求的顺序。

就是说,通过将请求包装在 NSOperation 中,您也许可以获得您想要的行为。如果您创建一个 NSOperationQueue,其 .maxConcurrentOperationCount1,您实际上创建了一个串行队列。然后使用您已经编写的相同循环,您应该能够像这样包装您的 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)
            }
     })
}
 

如果 .maxConcurrentOperationCount1,队列应该按顺序执行,正如我提到的。因此,根据 NSOperationQueue 的文档,您的操作将按照它们添加到队列中的顺序执行。所以你应该看到你想要的 1 到 30 的结果。

综上所述,对于您要解决的问题,可能有更好的解决方案,除非这仅仅是为了按顺序获得这些结果的编码练习。

关于ios - Alamofire 串行请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34934369/

相关文章:

ios - 调用 sizeToFit 时,UIButton 无法使用自定义字体正确调整高度

swift - 始终在get方法中登录成功

ios - HTTP POST 请求在 Alamofire 中的响应与 Jsoup 中的响应不同

ios - Alamofire 发布请求错误调用中的额外参数 'method'

ios - swift 2.0 与 Alamofire : How to send http headers with X-WSSE Authorization?

ios - 如何修复 "Dictionary literal contains duplicate keys "?

ios - UILabel 中的大小写不正确

ios - 无法检测到内存泄漏Xcode

ios - 将 XCTest 导入动态框架

ios - TableViews 和单独的列