3

I'm trying to upload a file to an AWS S3 bucket. If the upload fails for any reason, I want to be able to retry a few times.

I have a custom NSOperation, whose main method creates a AWSS3TransferManagerUploadRequest() instance. With the help of the AWSS3TransferManager, I start the upload.

If it fails, should I call main() in the task.completionBlock? Or should I have my NSOperation's completionBlock, and try restarting the operation from there? Here's some code for clarity

class PhotoUploadOperation: NSOperation {
var photoURL: NSURL!
var fileName: String!
var festival: PFObject!
var sleepTime: NSTimeInterval = 2.0
init(photoURL: NSURL, withFileName fileName:String, forFestival festival: PFObject) {
    super.init()
    self.photoURL = photoURL
    self.fileName = fileName
    self.festival = festival
}

override func main() {
    let uploadRequest = AWSS3TransferManagerUploadRequest()
    uploadRequest.bucket = "festivals123";
    uploadRequest.key = fileName
    uploadRequest.contentType = "image/jpeg"
    uploadRequest.body = photoURL
    uploadRequest.ACL = .PublicRead
    AWSS3TransferManager.registerS3TransferManagerWithConfiguration(DataManager.shared.awsConfiguration, forKey: "ID1")
    let transferManager = AWSS3TransferManager.S3TransferManagerForKey("ID1")

    let task = transferManager.upload(uploadRequest)
    task.continueWithBlock { (task: AWSTask!) -> AnyObject! in
        if (task.faulted) {
            print("now we need to restart upload for \(self.fileName)")
            NSThread.sleepForTimeInterval(self.sleepTime)
            if (self.sleepTime <= 2 ) {
                self.sleepTime = self.sleepTime*2
            }
            self.main()
        }

        return task
    }
}
}
Leo
  • 24,596
  • 11
  • 71
  • 92

1 Answers1

2

After asking a few colleagues, I guess the way is, let the operation complete with failure, and then create another operation to perform the same task.