如何重试 URLRequest.sharedDataTask 直到响应为 200?

How can I retry a URLRequest.sharedDataTask until the response is 200?

我是 Swift 的新手,目前在 httpResponse 为 200 时退出包含 shared.dataTask 的函数。我们将不胜感激。

func retryFunc(url: String, requestType: String, requestJsonData: Any, retriesLeft: Int) {
    //Function body
    // declarations
    while self.numberOfretries > 0 {
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print(error?.localizedDescription ?? "No data")
                return
            }            
            
            if let httpResponse = response as? HTTPURLResponse {
                print(httpResponse.statusCode)
                if httpResponse.statusCode == 200 {
                    print("Got 200")
                    self.numberOfretries = 0
                    let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
                    if let responseJSON = responseJSON as? [String: Any] {
                        print(responseJSON)
                    }
                    return
                }
                if httpResponse.statusCode == 500 {
                    print("Got 500")
                    self.numberOfretries -= 1
                    
                    self.retryFunc(url: url, requestType: <request-type>, requestJsonData: json, retriesLeft: self.numberOfretries)
                }
            }
        }
        task.resume()
    }
}
//calling function from another class
func retryFunc(url: <url>, requestType: <type>, requestJsonData: <jsonData>, retriesLeft: <3>)

我需要在获得 200 时退出函数,但它仍会继续 运行 调用函数时指定的重试次数。

考虑到 while 循环在异步任务之外,因此在计数器递减之前可以创建 100 个任务。

更好的方法是删除 while 循环并检查闭包内的 0 – retriesLeft 参数没有意义 – 例如

func retryFunc(url: String, requestType: String, requestJsonData: Any) {
    //Function body
    // declarations
    
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
                        
        if let error = error {
            print(error.localizedDescription)
            return
        }
                            
        if let httpResponse = response as? HTTPURLResponse {
           print(httpResponse.statusCode)
           if httpResponse.statusCode == 200 {
               print("Got 200")
               do {
                   if let responseJSON = try JSONSerialization.jsonObject(with: data!) as? [String: Any] {
                       print(responseJSON)
                   }
               } catch { print(error) }

           } else if httpResponse.statusCode == 500 {
               print("Got 500")
               self.numberOfretries -= 1
               if self.numberOfretries == 0 { return }
    
               self.retryFunc(url: url, requestType: requestType, requestJsonData: requestJsonData)
           }
       }
    }
    task.resume()
}