I'm looking for a good pattern with which I can chain multiple HTTP requests. I want to use Swift, and preferrably Alamofire.
Say, for example, I want to do the following:
It seems that the concept of promises may be a good fit for this. PromiseKit could be a good option if I could do something like this:
NSURLConnection.promise( Alamofire.request( Router.Put(url: "http://httbin.org/put") ) ).then { (request, response, data, error) in Alamofire.request( Router.Get(url: "http://httbin.org/get") ) }.then { (request, response, data, error) in // Process data }.then { () -> () in // Reload table }
but that's not possible or at least I'm not aware of it.
How can I achieve this functionality without nesting multiple methods?
I'm new to iOS so maybe there's something more fundamental that I'm missing. What I've done in other frameworks such as Android is to perform these operations in a background process and make the requests synchronous. But Alamofire is inherently asynchronous, so that pattern is not an option.
Alamofire is an HTTP network-based library which is used to handle the web request and response in iOS and MacOS. It is the wrapper class of URLSession and provides an interface on the top of Apple's networking stack. It simplifies the common networking tasks like preparing HTTP requests and parse the JSON object.
Networking in Alamofire is done asynchronously. 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. None of the response handlers perform any validation of the HTTPURLResponse it gets back from the server.
Alamofire is an HTTP networking library written in Swift. Alamofire helps to improve the quality of code. It is a simpler way to consume REST services. Alamofire is the basic tool for hundreds of projects.
Wrapping other asynchronous stuff in promises works like this:
func myThingy() -> Promise<AnyObject> { return Promise{ fulfill, reject in Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]).response { (_, _, data, error) in if error == nil { fulfill(data) } else { reject(error) } } } }
Edit: Nowadays, use: https://github.com/PromiseKit/Alamofire-
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