在iOS(Swift)上从AWS S3存储桶中并行下载对象

时间:2022-07-09 10:42:56

I am trying to download download several images in parallell from an S3 bucket and I want to know once all of them has finished. I am able to perform the download of an object using a function I have written with the following signature:

我试图从S3桶下载并行下载几个图像,我想知道所有这些图像完成后。我能够使用我用以下签名编写的函数来执行对象的下载:

func downloadImage(key: String) -> AWSTask

The AWSTask returned is this one from an instance of AWSS3TransferUtility:

返回的AWSTask是来自AWSS3TransferUtility实例的AWSTask:

downloadDataFromBucket:key:expression:completionHander:

I want to run some code when all of the downloads complete so I have tried this code:

我想在所有下载完成后运行一些代码,所以我尝试了这段代码:

for image in imageList {
    downloadTaskList.append(downloadImage(image))
}

AWSTask(forCompletionOfAllTasks:downloadTaskList).continueWithBlock {
        (task: AWSTask!) -> AnyObject! in
        print("All images downloaded")
        return nil
}

In this code imageList is a list of Strings and downloadTaskList is a list where all AWSTasks are appended to.

在此代码中,imageList是一个字符串列表,而downloadTaskList是一个列出所有AWSTasks的列表。

The problem is that it prints "All images downloaded" instantly, before the images are downloaded. I think this is because the AWSTask returned from downloadDataFromBucket is considered completet when the download starts not when it is completed. What AWSTask can I add to the list instead to make this work? I tried adding the completion handler of downloadDataFromBucket but it is not an AWSTask.

问题是它在下载图像之前立即打印“所有下载的图像”。我认为这是因为从downloadDataFromBucket返回的AWSTask在下载开始时不被认为是完整的。我可以将哪些AWSTask添加到列表中以使其工作?我尝试添加downloadDataFromBucket的完成处理程序,但它不是AWSTask。

1 个解决方案

#1


1  

I managed to make my own task using AWSTaskCompletionSource. I simply create a new task completion source at the top of my function:

我设法使用AWSTaskCompletionSource完成自己的任务。我只是在我的函数顶部创建一个新的任务完成源:

let taskCompletionSource = AWSTaskCompletionSource()

I return the corresponding task at the end of the function:

我在函数末尾返回相应的任务:

return taskCompletionSource.task

Lastly I set the task as completed in the completion handler:

最后,我在完成处理程序中将任务设置为已完成:

taskCompletionSource.setResult("Download Completed")

The completion handler also calls setError on the taskCompletionSource in the case of errors.

在出现错误的情况下,完成处理程序还会在taskCompletionSource上调用setError。

#1


1  

I managed to make my own task using AWSTaskCompletionSource. I simply create a new task completion source at the top of my function:

我设法使用AWSTaskCompletionSource完成自己的任务。我只是在我的函数顶部创建一个新的任务完成源:

let taskCompletionSource = AWSTaskCompletionSource()

I return the corresponding task at the end of the function:

我在函数末尾返回相应的任务:

return taskCompletionSource.task

Lastly I set the task as completed in the completion handler:

最后,我在完成处理程序中将任务设置为已完成:

taskCompletionSource.setResult("Download Completed")

The completion handler also calls setError on the taskCompletionSource in the case of errors.

在出现错误的情况下,完成处理程序还会在taskCompletionSource上调用setError。