我对Swift / iOS有些新意,并且一直在使用URLSession来对REST API进行网络调用。这是我用于发出网络请求的(稍微清理过的)代码:
enum ApiRequestError: Error {
case statusCodeOtherThan200(statusCode: Int)
// other error cases will be added here
}
enum ApiResponse {
case success(Data)
case failure(Error)
}
typealias myCompletionHandler = (ApiResponse) -> ()
func sampleRestCall(token: String, completionHandler: @escaping myCompletionHandler) {
let url = URL(string: "https://www.server.com")
// removed headers, parameters, etc. for brevity
let request = URLRequest(url: url!)
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
myCompletionHandler(.failure(error))
return
} else if let data = data, let response = response as? HTTPURLResponse {
if response.statusCode == 200 {
myCompletionHandler(.success(data))
} else {
print("Server returned unexpected response: \(response.statusCode) - (\(HTTPURLResponse.localizedString(forStatusCode: response.statusCode)))")
completionHandler(.failure(ApiRequestError.statusCodeOtherThan200(statusCode: response.statusCode)))
}
}
}.resume()
}
func testSampleRestCall() {
sampleRestCall(token: "12345678") { apiResponse in
switch apiResponse {
case .success(let data):
print("JSON response:")
if let jsonResponse = String(data: data, encoding: String.Encoding.utf8) {
print("\(jsonResponse)")
}
case .failure(let error):
print("Failure! \(error)")
}
}
}
代码运行良好,但我想知道如果失败,如何重试网络请求。我理解请求可能由于许多不同的原因而失败,但是为了这个问题,我想关注一个场景,其中失败只是暂时的,只需几秒钟后重试请求就可以解决。理想情况下,我想要一些“重试”包装器,这将允许我指定在放弃和通知用户之前应重试X次X次。作为一个附加功能,我可能会在每次重试之间插入一小段时间。我发现有几个类似这样的库,但我想了解如何自己做,而不仅仅是依靠库。如果有人对实现这种功能有任何建议,我当然会感激信息!
答案 0 :(得分:3)
试试这个
case .failure(let error):
print("Failure! \(error)")
if(self.counter<3)
{
self.testSampleRestCall()
counter = counter+1
}
else
{
// notify user check if this a thread other than main to wrap code in main queue
}
}