简体   繁体   English

Alamofire串行请求

[英]Alamofire Serial Requests

I need the requests to be executed in order, although this is not working using Alamofire. 我需要按顺序执行请求,尽管这不能使用Alamofire。

I want to print 1 to 30 in sequence (assuming the response is just an echo for the parameter) 我想按顺序打印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)
            }
     })

As per NSURLSessionConfiguration 's documentation: 根据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. 此外,根据您与Internet的连接,会话可能会使用低于您指定的下限。

The default value is 6 in OS X, or 4 in iOS. OS X中的默认值为6,iOS中的默认值为4。

As you can see, this setting merely controls the number of connections on a network level. 如您所见,此设置仅控制网络级别的连接数。 Once you queue up a number of requests using NSURLSession , which underlies Alamofire, it's up to that class to determine when your requests are made. 一旦使用NSURLSession排队了许多请求(这是Alamofire的基础),由该类决定何时发出请求。 There is no way, using NSURLSession or Alamofire, to guarantee the order in which requests are made without explicit coding them that way. 使用NSURLSession或Alamofire无法保证请求的顺序,而无需以这种方式对其进行显式编码。

That said, by wrapping the requests in NSOperation s you may be able to get the behavior you want. 也就是说,通过在NSOperation包装请求,您可以获得所需的行为。 If you create an NSOperationQueue with a .maxConcurrentOperationCount of 1 , you essentially create a serial queue. 如果您创建一个NSOperationQueue.maxConcurrentOperationCount1 ,其本质就是一个串行队列。 Then using the same loop you already wrote, you should be able to wrap your Alamofire requests like this: 然后使用您已编写的相同循环,您应该能够像这样包装您的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)
            }
     })
}

With a .maxConcurrentOperationCount of 1 , the queue should act serially, as I mentioned. 如果我提到,如果.maxConcurrentOperationCount1 ,则队列应该按.maxConcurrentOperationCount执行。 Therefore, your operations will execute in the order they were added to the queue, as per NSOperationQueue 's documentation. 因此,根据NSOperationQueue的文档,您的操作将按照添加到队列的顺序执行。 So you should see the the 1 to 30 result you want. 所以你应该看到你想要的1到30的结果。

All of this said, there is likely a better solution to the problem you want to solve, unless this is merely a coding exercise to get these results in order. 所有这些都说,对于你想要解决的问题,可能有更好的解决方案,除非这只是一个编码工作,以使这些结果有序。

As stated on Alamofire's Github page : 正如Alamofire的Github页面所述

Networking in Alamofire is done asynchronously. Alamofire中的网络是异步完成的。 Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are very good reasons for doing it this way. 对于不熟悉这个概念的程序员来说,异步编程可能会让人感到沮丧,但是有很好的理由这样做。

So, by nature of using Alamofire, you are going to get async network calls. 因此,就使用Alamofire而言,您将获得异步网络呼叫。 You could choose a different library or use the base SDK implementations, but as detailed in the Apple documentation link from Alamofire's Github page, there's a reason you're going to find almost every networking library is asynchronous. 您可以选择不同的库或使用基本SDK实现,但正如Alamofire的Github页面的Apple文档链接中所详述的那样,您可能会发现几乎每个网络库都是异步的。

So, to put it into context for you, the interface for Alamofire is receiving your calls synchronously, but past that, there's no guarantee what order the responses will get back to you in. They may make their request in a different order and they almost certainly will return responses in a different order. 所以,为了让它适合你,Alamofire的界面同步接收你的电话,但是在此之后,我们无法保证响应会回复你的订单。他们可能会以不同的顺序提出他们的请求肯定会以不同的顺序返回响应。

A better option here would be to store a mutable array of responses and once it has a response stored from each network call you made, sort the array and then do your print. 这里更好的选择是存储一个可变的响应数组,一旦它从你做的每个网络调用中存储一个响应,就对数组进行排序,然后进行打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM