简体   繁体   中英

Sequential Requests With Logic - Swift 3, Xcode 8, Alamofire 4

UPDATE: I a using SwiftEventBus https://github.com/cesarferreira/SwiftEventBus and this seems to work fine. I can simply define event listeners that wait on each step. Still interested in other approaches for multi-step login process.

I need to solve a multipart login process (stuck on how to wrap logic around serial GET/POST requests)

also on github as https://github.com/Alamofire/Alamofire/issues/1746

  • step 1 validate user/pw with basic authentication header
  • step 2 use returned token (from step 1) in new authentication header and fetch from server a list
  • step 3 user selects from returned list (or does another request to
    create new if thing not found on list) - note really important what the list is because I am just interested in the serialization and wrapping logic across steps
  • step 4 use guid from selected/created thing to generate auth token to fetch yet another new general use auth token and refresh token

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. 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. Open to a suggestion without Alamofire in order to learn how to do this.

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.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.

There is also a PromiseKit extension and a RxSwift extenstion for Alamofire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM