I am trying to give a time limit of 2 seconds and total trials of 3 for an async network call to execute and finish. and after the 2 seconds, the call should try one more time then exists with a failure.
I tried this. but its not exiting with an error after the two seconds. which makes sense since I am checking for deadline before firing the async call. but not sure how else to approach it.
func getDetails() async {
// maximum amounts of trials
let maxRetryCount = 2
let deadlineInSec = 1
for _ in 0..<maxRetryCount {
guard !self.isSuccess else {
break
}
do {
// setting deadline for 2 secs
if let deadline = Calendar.current.date(byAdding: .second,
value: deadlineInSec,
to: Date()),
Date() >= deadline {
throw TaskRetryingError.timedOut
}
let response = try await networkCall()
await MainActor.run {
self.data = data
self.isSuccess = true
}
} catch {
// If any error occurs, other than
if error as? TaskRetryingError != TaskRetryingError.exceededMaxRetryCount{
continue
}
// handling error.
}
}
}