所以当我的上传请求失败时,我对如何实现重试逻辑感到有点迷失.
这是我的代码,我想要一些指导如何做到这一点
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() }) }
这是一个通用解决方案,可以应用于任何没有参数的异步函数,但回调除外.我只通过成功和失败回调来简化逻辑,进步不应该难以添加.
所以,假设你的函数是这样的:
func startUploading(success: Void -> Void,failure: NSError -> Void) { DDLogDebug("JogUploader: Creating jog: \(self.jog)") API.sharedInstance.createJog(self.jog,failure: { error in failure(error) },success: {_ in success() }) }
匹配它的重试功能如下所示:
func retry(numberOfTimes: Int,task: (success: Void -> Void,failure: NSError -> Void) -> Void,success: Void -> Void,failure: NSError -> Void) { task(success: success,failure: { error in // do we have retries left? if yes,call retry again // if not,report error if numberOfTimes > 1 { retry(numberOfTimes - 1,task: task,success: success,failure: failure) } else { failure(error) } }) }
并且可以像这样调用:
retry(3,task: startUploading,success: { print("Succeeded") },failure: { err in print("Failed: \(err)") })
如果它一直失败,上面将重试startUploading三次,否则将在第一次成功时停止.
编辑.具有其他参数的函数可以简单地嵌入到闭包中:
func updateUsername(username: String,failure: NSError -> Void) { ... } retry(3,{ success,failure in updateUsername(newUsername,success,failure) },success: { print("Updated username") },failure: { print("Failed with error: \($0)") } )