繁体   English   中英

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

[英]How to download the image from URL array and append it to an array one by one Swift

我尝试从URL数组下载图像,并将该图像附加到图像数组中以进行收藏。 但它不会将其一一下载并附加到图像阵列。 所以我尝试使用调度组,但是不起作用。 添加调度组的正确方法是什么?

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()
        }
    }
}

打印:顺序错误

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

...

您的问题是group.notify将阻塞,直到调度组为空。 但是,在调用任何“叶子”之前,您都要用三个“输入”填充它,以使“通知”在第三个“离开”发生之前不会发生。

而是“通知”您需要使用“等待”。 要使用“等待”,您需要将整个内容放入新的后台线程中。

更新后的代码应类似于以下内容:

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()
        }
    }
}

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

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()
            })
    }
}

我的意思是对我来说,它真的像一种魅力一样工作,我有一个tableview, 其中 tableview的一个单元格包含Collection View

暂无
暂无

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

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