gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:43:57 26 4
gpt4 key购买 nike

我尝试从 URL 数组下载图像并将图像附加到我的 Collection View 的图像数组。但它不会将其一张一张地下载并附加到图像数组中。所以我尝试使用调度组,但没有用。添加调度组的正确方法是什么?

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

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

关于ios - 如何从 URL 数组下载图像并将其逐个附加到数组 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49269010/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com