I'm somewhat new to Swift/iOS and have been working with URLSession to make a network call to a REST API. Here's the (slightly cleaned up) code that I'm using to make the network request:
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)")
}
}
}
The code works well enough but I'm wondering about how to retry a network request if it fails. I understand that a request could fail for lots of different reasons but for the sake of this question, I'd like to focus on a scenario where the failure is only temporary and could be solved simply by retrying the request after a few seconds. Ideally, I'd like to have some kind of "retry" wrapper that will allow me to specify that a call should be retried X times before giving up and notifying the user. As an added feature, I would probably insert a small wait between each retry. I've found a couple of libraries that do something like this but I'd like to understand how to do it myself rather than just relying on a library. If anyone has a suggestion on achieving this kind of functionality, I would certainly appreciate the info!
Try this
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With