I am creating a seperate class to handle my Amazone S3 upload request. However, I am not too sure about the syntax to allow me to create a progress block before completion handler (as shown below in IBAction). Basically what I wish to achieve is inside my VC, I do the following:
@IBAction startUpload() {
let uploadPost = PostUpload(imageNSData: someNSData)()
uploadPost.uploadBegin {
// Some block here to grab the "progress_in_percentage" variable so I can use it on progress bar
{
// Some completion block when the request is completed and check if any error was returned
}
}
}
This is the structure of PostUpload class
class PostUpload {
var imageNSData: NSData!
init(imageNSData: NSData) {
self.imageNSData = imageNSData
}
func uploadBegin(completion:(success: Bool, error: NSError?) -> Void) {
// 1. Create upload request
let uploadRequest = AWSS3TransferManagerUploadRequest(
// Track progress through an AWSNetworkingUploadProgressBlock
uploadRequest?.uploadProgress = {[weak self](bytesSent:Int64, totalBytesSent:Int64, totalBytesExpectedToSend:Int64) in
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
let progress_in_percentage = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
print(progress_in_percentage)
})
}
// 3. Upload to Amazone S3
let transferManager = AWSS3TransferManager.defaultS3TransferManager()
transferManager.upload(uploadRequest).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task: AWSTask) -> AnyObject? in
if let error = task.error {
completion(true, error)
} else {
completion(true, nil)
}
return nil
})
}
}
Change your method to this:
func uploadBegin(progressUpdate: ((percent: Float) -> Void)? = nil, completion:(success: Bool, error: NSError?) -> Void) {
// 1. Create upload request
let uploadRequest = AWSS3TransferManagerUploadRequest(
// Track progress through an AWSNetworkingUploadProgressBlock
uploadRequest?.uploadProgress = {[weak self](bytesSent:Int64, totalBytesSent:Int64, totalBytesExpectedToSend:Int64) in
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
let progress_in_percentage = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
print(progress_in_percentage)
//Call this to update progress
progressUpdate?(progress_in_percentage)
})
}
// 3. Upload to Amazone S3
let transferManager = AWSS3TransferManager.defaultS3TransferManager()
transferManager.upload(uploadRequest).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task: AWSTask) -> AnyObject? in
if let error = task.error {
completion(true, error)
} else {
completion(true, nil)
}
return nil
})
}
Usage:
uploadBegin { (success, error) in
//completion block
}
Or:
uploadBegin({ (percent) in
//Update Progress on UI
}) { (success, error) in
//completion block
}
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