Is there a way to do Alamofire requests with retries

后端 未结 4 1995
离开以前
离开以前 2020-12-15 09:09

I have a lot of places in the code where Alamofire request/response are handled.

Each of this requests may fail because of some intermittent problem (the most commo

4条回答
  •  失恋的感觉
    2020-12-15 09:42

    One of the bits of syntactic sugar you get with Swift is you can use this:

    public func updateEvents(someNormalParam: Bool = true, someBlock: (Void->Void))
    

    Like this:

    updateEvents(someNormalParam: false) {...}
    

    Note the block is outside the () of the updateEvents function, contrary to where you'd normally expect it. It works only if the block is the last thing in the declaration of the function.

    That means if you happen to have a block such as your Alamofire request, you can effectively wrap it with your retry functionality. One slightly complicating issue is you want to call a block within the block. Not a big deal:

    func retryWrapper(alamoBlock: (Void->Request)) {
       alamoblock().responseJSON() {
           //Your retry logic here
       }
    }
    

    And you use it like so:

    retryWrapper() {
        Alamofire.request(method, targetUrl, parameters: parameters, encoding: encoding)
    }
    

    Meaning all you have to do is find your Alamofire calls and wrap them in { } and put retryWrapper() before. The retry logic itself is only there once.

提交回复
热议问题