快速“重试”逻辑要求 [英] Swift "retry" logic on request
问题描述
因此,当我的上传请求失败时,我对如何实现重试逻辑有些迷茫。
So i'm a bit lost on how to implement a retry logic when my upload request fail.
这是我的代码,我想了解如何
Here is my code i would like some guidance on how to do it
func startUploading(failure failure: (NSError) -> Void, success: () -> Void, progress: (Double) -> Void) {
DDLogDebug("JogUploader: Creating jog: \(self.jog)")
API.sharedInstance.createJog(self.jog,
failure: { error in
failure(error)
}, success: {_ in
success()
})
}
推荐答案
这是一个通用解决方案,可以应用于任何不带参数的异步函数,回调除外。我仅通过成功
和失败
回调,进度$ c来简化了逻辑$ p>应该不难添加。
Here's a general solution that can be applied to any async function that has no parameters, excepting the callbacks. I simplified the logic by having only success
and failure
callbacks, a progress
should not be that hard to add.
因此,假设您的函数是这样的:
So, assuming that your function is like this:
func startUploading(success: @escaping () -> Void, failure: @escaping (Error) -> Void) {
DDLogDebug("JogUploader: Creating jog: \(self.jog)")
API.sharedInstance.createJog(self.jog,
failure: { error in
failure(error)
}, success: {_ in
success()
})
}
匹配的 retry
函数可能看起来像这样:
A matching retry
function might look like this:
func retry(times: Int, task: (success: @escaping () -> Void, failure: @escaping (Error) -> Void) -> Void, success: @escaping () -> Void, failure: @escaping (Error) -> Void) {
task(success: success,
failure: { error in
// do we have retries left? if yes, call retry again
// if not, report error
if times > 0 {
retry(times - 1, task: task, success: success, failure: failure)
} else {
failure(error)
}
})
}
可以这样称呼:
retry(times: 3, task: startUploading,
success: {
print("Succeeded")
},
failure: { err in
print("Failed: \(err)")
})
上面的操作如果仍然失败,将重试 startUploading
调用三次,否则将在第一次成功时停止。
The above will retry the startUploading
call three times if it keeps failing, otherwise will stop at the first success.
编辑。确实具有其他参数的函数可以简单地嵌入到闭包中:
Edit. Functions that do have other params can be simply embedded in a closure:
func updateUsername(username: String, success: @escaping () -> Void, failure: @escaping (Error) -> Void) {
...
}
retry(times: 3, { success, failure in updateUsername(newUsername, success, failure) },
success: {
print("Updated username")
},
failure: {
print("Failed with error: \($0)")
}
)
这篇关于快速“重试”逻辑要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!