连锁多个Alamofire请求 [英] Chain multiple Alamofire requests

查看:345
本文介绍了连锁多个Alamofire请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个可以链接多个HTTP请求的好模式。我想使用Swift,最好是 Alamofire

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例如,我想执行以下操作:

Say, for example, I want to do the following:


  1. 发出PUT请求

  2. 发出GET请求

  3. 重新加载数据表

似乎 promises 可能非常适合这种情况。如果我可以这样做, PromiseKit 可能是一个不错的选择:

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?

我是iOS的新手,所以也许有一些我缺少的基础知识。我在其他框架(如Android)中所做的是在后台进程中执行这些操作并使请求同步。但 Alamofire本质上是异步的,因此该模式不是一种选择。

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.

推荐答案

在promises中包装其他异步内容的方式如下:

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)
            }
        }
    }
}

编辑:现在,使用: https://github.com/PromiseKit/Alamofire-

这篇关于连锁多个Alamofire请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆