将JSON请求循环到后端REST API

问题描述

我正在向后端(REST API)发送请求。我的任务:如果JSON响应未采用要求的格式或返回错误,则启动请求周期-3次尝试,如果这3次尝试均失败,则退出,否则继续下一个(HomePage)

这是代码

func checkUsers(){
    
let headers: HTTPHeaders = ["Content-Type" : "application/json"]
NetworkManager.sharedInstance.manager.request("https://restapi.com/user",method: .get,parameters: nil,encoding: JSONEncoding.default,headers: headers).responseJSON { (response) -> Void in

switch response.result {
    case .success(let value):
    let response = JSON(value)

    print("JSON Response: \(response)")

    if response["operation"].stringValue == "loginerror" {
        print("Error")
        
        self.showNotRegisteredScreen()
        
    } else {

    usersFIO = response["userName"].stringValue
    
    self.didFinishLogin()
}

case .failure(let error):
    print("fail to fecth data",error)

    self.showErrorScreen()
}
}

请告诉我如何开始一个请求周期,在其中指定三个尝试

P.S .:使用Alamofire和SwiftyJson吊舱

谢谢!

解决方法

它对我来说适用于Alamofire 5

lazy var manager: Alamofire.Session = {
            let configuration = URLSessionConfiguration.default
            
            let retryPolicy = RetryPolicy(retryLimit: 3)
            let interceptor = Interceptor(retriers: [retryPolicy])
            
            let manager = Alamofire.Session(configuration: configuration,interceptor: interceptor,serverTrustManager: serverTrustManager,eventMonitors: [CertificateAuthAdapter()])
            return manager
        }()