jlhonora jlhonora - 5 months ago 634
iOS Question

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:

Router.Put(url: "http://httbin.org/put")
).then { (request, response, data, error) in
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.


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 {
            } else {