我正在创建一个单独的类来处理我的 Amazone S3 上传请求。但是,我不太确定允许我在完成处理程序之前创建进度 block 的语法(如下面的 IBAction
所示)。基本上我希望实现的是在我的 VC 中,我执行以下操作:
@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
}
}
}
这是PostUpload类的结构
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
})
}
}
最佳答案
将您的方法更改为:
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
})
}
用法:
uploadBegin { (success, error) in
//completion block
}
或者:
uploadBegin({ (percent) in
//Update Progress on UI
}) { (success, error) in
//completion block
}
关于ios - 正确的语法以在完成处理程序之前创建进度 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39523804/