我有一个运行循环的函数,它会为循环中的每个项目触发另一个函数,但它似乎没有像数组中的项目那样多次运行该函数。
这是我的函数。
func startLoop(completion: @escaping (_ finished: Bool) -> ()) {
print("Tony items amount is \(tempImgUrls.count)")
for item in tempImgUrls {
dispatchGroup.enter()
print("Tony begin loop")
let img = item["imgUrl"]
let name = item["name"]
downloadImages(img: img!, name: name!, completion: { (complete) in
print("Tony mid loop")
self.dispatchGroup.leave()
})
}
dispatchGroup.notify(queue: DispatchQueue.main) {
print("Tony end loop")
completion(true)
}
}
func downloadImages(img: String, name: String, completion: @escaping (_ finished: Bool) -> ()) {
imageShown.sd_setImage(with: URL(string: img), completed: { (image, error, cacheType, imageUrl) in
let personImg = image!
let personId = name
let post = Person(personImage: personImg, personId: personId)
self.finalImgUrls.append(post)
completion(true)
print("Tony array is with images person is \(self.finalImgUrls)")
print("Tony items 2 amount is \(self.finalImgUrls.count)")
})
}
}
这是在 consol 中打印出来的,正如您所看到的,它首先打印循环开始,然后是中间 1 次和结束 1 次,最后附加一个项目而不是像输入的那样是 4 个项目。
Tony items amount is 4
Tony begin loop
Tony begin loop
Tony begin loop
Tony begin loop
Tony mid loop
Tony array is with images person is [AppName.Person]
Tony items 2 amount is 1
最佳答案
您那里的代码正在运行。问题似乎是 sd_setImage
只提供一次结果。
如何测试
如果您按如下方式使用 sd_setImage
的测试实现,那么您会得到预期的结果:
class SomeClass {
func sd_setImage(with url: URL?, completed: @escaping (UIImage?, Error?, String, URL) -> Void) {
let random = Double(arc4random()) / Double(UINT32_MAX)
DispatchQueue.main.asyncAfter(deadline: .now() + random, execute: {
completed(UIImage(), nil, "a", url!)
})
}
}
关于ios - Loop 不使用调度队列、iOS、Swift 完成循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53343019/