Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain multiple Alamofire requests

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:

  1. Make a PUT request
  2. Make a GET request
  3. Reload table with data

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.

like image 776
jlhonora Avatar asked Feb 20 '15 17:02

jlhonora


People also ask

What does Alamofire mean?

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.

Is Alamofire an asynchronous?

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.

What is the use of Alamofire in Swift?

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.


1 Answers

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-

like image 172
mxcl Avatar answered Sep 30 '22 06:09

mxcl