有没有办法通过重试做Alamofire请求 [英] Is there a way to do Alamofire requests with retries

查看:1108
本文介绍了有没有办法通过重试做Alamofire请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中有很多地方处理Alamofire请求/响应。

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 common is flaky network).

我希望能够在纾困前重试请求3次。

I would like to be able to retry requests 3 times before bailing out.

直截了当的方法是有这样的东西

The straightforward method would be to having something like that

var errorCount = 0
func requestType1() {
   let request = Alamofire.request(...).responseJSON { response in
       if (isError(response) && errorCount < 3) {
          errorCount += 1
          request1()
       } 
       if (isError(response)) {
          handleError()
       }

       handleSuccess()
   }
}

但是,出于多种原因,我不喜欢这种方法。最明显的是我需要为每个请求类型实现这样的代码(我有15个这样的代码)。

However, I dislike this approach A LOT for multiple reasons. The most obvious is that I will need to implement such code for each request type (and I have something like 15 of them).

我很好奇是否有办法做类似的事情(变化很小且非侵入性)

I am curios whether there is way to do something like (where the changes are minimal and non intrusive)

let request = Alamofire.request(..., **3**) 


推荐答案

语法糖的一点点你使用Swift就可以使用它:

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

像这样:

updateEvents(someNormalParam: false) {...}

请注意,该块位于updateEvents函数的()之外,与您通常期望的位置相反。它只有在块是函数声明中的最后一件事时才有效。

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.

这意味着如果你碰巧有一个像你的Alamofire请求这样的块,你可以有效地用你的重试功能包装它。一个稍微复杂的问题是你想在块内调用一个块。没什么大不了的:

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

你这样使用它:

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

意味着你所要做的就是找到你的Alamofire调用并将它们包装在{}中并放入retryWrapper()之前。重试逻辑本身只有一次。

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.

这篇关于有没有办法通过重试做Alamofire请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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