我使用AWS Mobile SDK在应用程序中有文件下载代码。
显示带有下载进度和取消按钮的警报。它正在工作,但是当用户单击警报取消按钮时,我需要取消下载。我试图使用AWSS3TransferUtilityDownloadTask和AWSS3TransferUtilityTask对象取消任务,但似乎无法正常工作,它可以为我带来进步并完成下载。
这是我文件下载的工作代码。
请建议我如何取消我的下载请求。
let credentialProvider = AWSStaticCredentialsProvider(accessKey: "MyAccessKey", secretKey: "MySecretKey")
let configuration = AWSServiceConfiguration(region: AWSRegionType.USEast1, credentialsProvider: credentialProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
let expression = AWSS3TransferUtilityDownloadExpression()
expression.progressBlock = {(task, progress) in DispatchQueue.main.async(execute: {
// Do something e.g. Update a progress bar.
print("File Progress:",Float(progress.fractionCompleted))
let progress = Float(progress.fractionCompleted)
DispatchQueue.main.async {
if progress == 1.0 {
self.globalAlert.dismiss(animated: true, completion: nil)
}else{
self.globalProgressView!.progress = progress
self.msgProgress = String(Int(progress*100))
}
}
})
}
var completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock?
completionHandler = { (task, URL, data, error) -> Void in
DispatchQueue.main.async(execute: {
// Do something e.g. Alert a user for transfer completion.
// On failed downloads, `error` contains the error object.
//My other code stuff execution
})
}
var refUploadTask: AWSS3TransferUtilityTask?
let transferUtility = AWSS3TransferUtility.default()
transferUtility.downloadData(
fromBucket: Bucket_Name,
key: fileKey,
expression: expression,
completionHandler: completionHandler
).continueWith {
(task) -> AnyObject? in if let error = task.error {
print("Error: \(error.localizedDescription)")
}
if let _ = task.result {
// Do something with downloadTask.
print("download started..")
DispatchQueue.main.async(execute: {
self.globalAlert = UIAlertController(title: "Downloading...", message: "\(String(describing: self.msgProgress))% Completed", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: {
(action : UIAlertAction!) -> Void in
self.refUploadTask.cancel()
})
// Show it to your users
self.globalAlert.addAction(cancelAction)
self.present(self.globalAlert, animated: true, completion: {
// Add your progressbar after alert is shown (and measured)
let margin:CGFloat = 8.0
let rect = CGRect(x: margin, y: 72.0, width: self.globalAlert.view.frame.width - margin * 2.0 , height: 2.0)
self.globalProgressView = UIProgressView(frame: rect)
self.globalProgressView!.tintColor = .blue
self.globalAlert.view.addSubview(self.globalProgressView!)
})
})
}
return nil;
}
最佳答案
您可以获取AWSS3TransferUtilityDownloadTask对象并取消正在进行的下载。
let awsTask = transferUtility.getDownloadTasks()
if let taskArray = awsTask.result {
for idx in taskArray {
if let task = idx as? AWSS3TransferUtilityDownloadTask {
task.cancel()
}
}
}
关于ios - AWSS3 Mobile SDK迅速取消文件下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57655354/