[英]Sequential Requests With Logic - Swift 3, Xcode 8, Alamofire 4
I need to solve a multipart login process (stuck on how to wrap logic around serial GET/POST requests) 我需要解决一个多部分的登录过程(坚持如何围绕串行GET / POST请求包装逻辑)
also on github as https://github.com/Alamofire/Alamofire/issues/1746 也在github上作为https://github.com/Alamofire/Alamofire/issues/1746
I can do each of these individually (set headers, set parms, validate and parse result, etc), BUT I do not understand how to create the logic flow around the requests. 我可以单独执行每个操作(设置标头,设置参数,验证和解析结果等),但是我不了解如何围绕请求创建逻辑流。 Do I have to nest all of the requests inside each other so that I step 2 happens inside step 1, step 3 happens inside step 2, etc. Or is there a simple example application somewhere that shows how execute multiple requests with logic around the requests - Not interested in simply queueing the requests as I have to run logic around the requests. 我是否必须将所有请求相互嵌套,以便我的步骤2发生在步骤1内,步骤3发生在步骤2内,依此类推?还是在某个地方有一个简单的示例应用程序显示了如何围绕请求执行逻辑上的多个请求-对仅排队请求不感兴趣,因为我必须围绕请求运行逻辑。 Event Bus? 活动巴士? Managed queue? 托管队列? Other? 其他? Looking for guidance and ideally a downloadable sample app that I can play with and learn from. 寻找指导,理想情况下是一个可下载的示例应用程序,我可以使用它并从中学习。
I originally built this without Alamofire and had the request timing/logic problem and thought Alamofire might make this easier but after switching to Alamofire I find myself stuck at the same point. 我最初是在没有Alamofire的情况下构建此程序的,并且遇到了请求计时/逻辑问题,并认为Alamofire可能会使此操作变得更容易,但是切换到Alamofire后,我发现自己陷入了同样的境地。 Open to a suggestion without Alamofire in order to learn how to do this. 公开征求没有Alamofire的建议,以学习如何执行此操作。
This is not build into Alamofire per se because it is callback based but you can use the callbacks and nest each call to Alamofire into the other like that: 这本身并没有内置在Alamofire中,因为它是基于回调的,但是您可以使用这些回调并将对Alamofire的每个调用嵌套到另一个中,如下所示:
Alamofire.request("url").responseJSON { _ in
Alamofire.request("anotherUrl").responseJSON { _ in
Alamofire.request("yetAnotherUrl").responseJSON { _ in
//all three have finished with either response or error
}
}
}
This leads to a pattern often seen with callbacks that is also sometimes referred to as Pyramid of doom. 这会导致在回调中经常看到一种模式,有时也称为“厄运金字塔”。
As an alternative you can check out either Promises or I like to use a reactive library like RxSwift that will give your code more of a 'waterfall' look. 作为替代方案,您可以签出Promises,或者我喜欢使用像RxSwift这样的反应式库,它将为您的代码提供更多的“瀑布”外观。
There is also a PromiseKit extension and a RxSwift extenstion for Alamofire. 还为Alamofire提供了PromiseKit扩展和RxSwift扩展 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.