如何从URL数组下载图像并将其逐个附加到数组Swift

时间:2018-03-14 02:47:55

标签: ios swift grand-central-dispatch

我尝试从URL数组下载图像,并将图像附加到我的集合视图的图像数组中。但它不会下载并逐个附加到图像阵列。所以我尝试使用调度组,但没有工作。添加Dispatch组的正确方法是什么?

func downloadPhoto(){
    progressImgArray.removeAll() // this is the image array
    for i in 0..<progressArray.count{
        let urls = URL(string: progressArray[i].userProgressImage) // this is the URL array
        let group = DispatchGroup()

        print(urls ?? "nil image")
        print("-------GROUP ENTER-------")

        group.enter()
        URLSession.shared.dataTask(with: urls!, completionHandler: { data, response, error in

            print(response?.suggestedFilename ?? urls?.lastPathComponent ?? "nil image")

            if let imgData = data {
                if UIImage(data: imgData) != nil {
                    DispatchQueue.main.async() {
                        self.progressImgArray.append(UIImage(data: data!)!)
                    }
                }
            }

            group.leave()
        }).resume()

        group.notify(queue: .main) {
            self.collectionView.reloadData()
        }
    }
}

PRINTED:序列错误

http://sweat.asia/app/users_progresses/users_progresses_111_761319316286fcb38a0b.png
-------GROUP ENTER-------
http://sweat.asia/app/users_progresses/users_progresses_111_263983427965d44f5021.png
-------GROUP ENTER-------
http://sweat.asia/app/users_progresses/users_progresses_111_3361893721fa8f84015a.png
-------GROUP ENTER-------
users_progresses_111_263983427965d44f5021.png
users_progresses_111_761319316286fcb38a0b.png
users_progresses_111_3361893721fa8f84015a.png

如何使它像这样

http://sweat.asia/app/users_progresses/users_progresses_111_761319316286fcb38a0b.png
    -------GROUP ENTER-------
users_progresses_111_761319316286fcb38a0b.png

http://sweat.asia/app/users_progresses/users_progresses_111_263983427965d44f5021.png
    -------GROUP ENTER-------
users_progresses_111_263983427965d44f5021.png

...

2 个答案:

答案 0 :(得分:3)

您的问题是group.notify将阻止,直到调度组为空。但你填写三个&#34;进入&#34;在任何&#34;离开&#34;之前被叫,所以&#34;通知&#34;直到第三个&#34;离开&#34;才会发生。发生的情况。

相反&#34;通知&#34;你需要使用&#34;等待&#34;。并使用&#34;等待&#34;你需要将整个事情放在一个新的后台线程中。

更新后的代码应如下所示:

func downloadPhoto(){
    DispatchQueue.global().async {
        progressImgArray.removeAll() // this is the image array

        for i in 0..<progressArray.count {
            guard let url = URL(string: progressArray[i].userProgressImage) else {
                continue
            }

            let group = DispatchGroup()

            print(url)
            print("-------GROUP ENTER-------")

            group.enter()
            URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in
                print(response?.suggestedFilename ?? url.lastPathComponent)

                if let imgData = data, let image = UIImage(data: imgData) {
                    DispatchQueue.main.async() {
                        self.progressImgArray.append(image)
                        self.collectionView.reloadData()
                    }
                } else if let error = error {
                    print(error)
                }

                group.leave()
            }).resume()

            group.wait()
        }
    }
}

我还做了其他一些改进,包括更好地处理选项。

答案 1 :(得分:0)

对rmaddy答案的小更新:

  

当阵列中已下载的图像已满时获取通知。

func downloadImageFromUrl()
{
    DispatchQueue.global().async
        {
            self.imageArray.removeAll()
            let dispatchGroup = DispatchGroup()

            for i in 0..<(self.imageUrlArray?.count)!
            {
                guard let url = URL(string: (self.imageUrlArray?![i])!)
                    else{ continue }

                dispatchGroup.enter()
                Alamofire.request(url).responseData(completionHandler: { response in

                    guard
                        let data = response.result.value,
                        let image = UIImage(data:data)
                        else {
                            print("Error in downlaoding images : ",(response.error?.localizedDescription)!)
                            return
                    }
                    DispatchQueue.main.async {
                        self.imageArray.append(image)
                    }
                    dispatchGroup.leave()
                })
                dispatchGroup.wait()
            }
            dispatchGroup.notify(queue: DispatchQueue.main,execute: {
                print("are we done.... :",self.imageArray.count)
                self.yourCollection.reloadData()
            })
    }
}
  

我的意思是,它真的像一种魅力一样工作,我在中拥有一个表格视图,该表格视图的其中一个单元格包含“收藏夹视图”