简体   繁体   English

按顺序异步下载图像

[英]Downloading Images Asynchronously in Sequence

I am trying to download images but it is crucial that the images I download are in a specific order. 我正在尝试下载图像,但下载的图像按特定顺序排列至关重要。 I am using the following code to download the image: 我使用以下代码下载图像:

func downloadImage(url: NSURL, completionHandler: (response: UIImage) -> ()){
    print("Started downloading \"\(url.URLByDeletingPathExtension!.lastPathComponent!)\".")
    manager.getDataFromUrl(url) { (data, response, error)  in
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            guard let data = data where error == nil else { return }
            print("Finished downloading \"\(url.URLByDeletingPathExtension!.lastPathComponent!)\".")
            completionHandler(response: UIImage(data: data)!)
        }
    }
}

and I am using this code to call downloadImage 我正在使用此代码调用downloadImage

self.downloadImage(NSURL(string: self.url)!, completionHandler: { response in
                            dispatch_async(dispatch_get_main_queue()) {
                                self.images.append(response)
                            }
                        })

The problem is that the images start downloading in the correct order however the response isn't (this is obviously because the size of the images are different and one comes in faster). 问题是图像开始以正确的顺序下载但是响应不是(这显然是因为图像的大小不同而且图像的速度更快)。 So what is happening is that all images start downloading, and whichever comes first appends to the images : [UIImage] array. 所以正在发生的是所有图像开始下载,并且首先附加到images : [UIImage]数组。 How can I make it so that the images in the images array is in order? 我怎样才能使images数组中的images按顺序排列?

I've also tried to remove the main block when calling downloadImage function 我还试图在调用downloadImage函数时删除主块

self.downloadImage(NSURL(string: self.url)!, completionHandler: { response in                     
             self.images.append(response)
       })

You cannot control the download order in the sense that all the requests to the same server will be pipelined no matter what the order you create the URL objects in. Also, some URLs may be cached while others may need to go to the remote server. 无论您创建URL对象的顺序如何,对同一服务器的所有请求都将被流水线化,您无法控制下载顺序。此外,某些URL可能会被缓存,而其他URL可能需要转到远程服务器。 What you need to do is maintain a mutable array or dictionary that contains the url to actual data mapping, then wait until all the urls have been completely downloaded and then iterate in a known order. 您需要做的是维护一个包含实际数据映射URL的可变数组或字典,然后等待所有URL完全下载,然后按已知顺序迭代。

The simplest method is that you can save every image in Dictionary with their url after downloading. 最简单的方法是,您可以在下载后使用其URL保存Dictionary每个图像。 Like var imageData = [String: NSData]() . var imageData = [String: NSData]() Later you can sort it or use it by keys(url). 稍后您可以对其进行排序或按键(url)使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM