I need the requests to be executed in order, although this is not working using Alamofire.
I want to print 1 to 30 in sequence (assuming the response is just an echo for the parameter)
// 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:
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.
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. There is no way, using NSURLSession or Alamofire, to guarantee the order in which requests are made without explicit coding them that way.
That said, by wrapping the requests in NSOperations you may be able to get the behavior you want. If you create an NSOperationQueue with a .maxConcurrentOperationCount of 1, you essentially create a serial queue. Then using the same loop you already wrote, you should be able to wrap your Alamofire requests like this:
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. Therefore, your operations will execute in the order they were added to the queue, as per NSOperationQueue's documentation. So you should see the the 1 to 30 result you want.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With