Alamofire是一种通用的重试模式 - 当http超时时

时间:2017-06-19 13:28:52

标签: swift alamofire

我有以下解决方案用于重试 - 使用Alamofire获取数据。这是服务器在指定的秒数内减慢服务的时间。

这是正常的,但我想让它更干净 - 因为我有很多端点。你能看到我如何改进这一点,比如将代码移动到基类 - 但是如何从基类重新调用同一个超类端点。

欢迎任何改进 - 谢谢

端点(缓慢且将超时)类

<p class="smallText myclass_1 myclass_2">

端点基类:

import Foundation
import AlamofireObjectMapper
import Alamofire

public class EndpointSlow: BaseEndpoint {

    public override init(){

    }

    public func getSlow(completionClosure: @escaping (_ items: EndpointEntity?) -> () ) {

        let url = self._url + "/slow/file.json"

        let headers: HTTPHeaders = [
            "Content-Type" : "application/x-www-form-urlencoded",
            "Accept": "application/json"
        ]

        Singleton.sharedInstance.pdAlamofire.request(
            url,
            method: .get,
            headers: headers).responseObject { (response: DataResponse<EndpointEntity>) in

                let obj = response.result.value

                switch (response.result) {
                case .success:
                    print("Slow... done")
                    self.resetRetry()
                    completionClosure(obj)
                    break
                case .failure(let error):
                    if error._code == NSURLErrorTimedOut {
                        print("Timeout...")

                        if self.shouldRetry(){
                            self.getSlow(completionClosure: { (endpointEntity: EndpointEntity?) in
                                completionClosure(endpointEntity)
                            })
                        }else{
                            print("Error handeling...")
                        }

                    }
                    print("\n\nAuth request failed with error:\n \(error)")
                    break
                }


        }

    }

}

最后我有一个Singleton,我设置了Alamofire SessionManager:

import Foundation
import Alamofire

public class BaseEndpoint{
    let _url = "http://localhost:8080"

    let retry = Singleton.sharedInstance.retryCount
    var retryCount: Int = 0


    public func showReloadingAnimation(){

    }

    public func hideReloadingAnimation(){


    }

    public func resetRetry() {

        self.hideReloadingAnimation()
        self.retryCount = 0

    }

    public func shouldRetry() -> Bool {
        if (self.retryCount <= self.retry){
            self.retryCount = self.retryCount+1
            return true
        }else{
            self.retryCount = 0
            return false
        }
    }

}

0 个答案:

没有答案