gpt4 book ai didi

ios - 循环的 Swift 4 完成处理程序不起作用

转载 作者:行者123 更新时间:2023-11-28 09:31:03 24 4
gpt4 key购买 nike

在 swift 4 中,我有这个方法,它使用完成处理程序进行循环:

func loopImages(qa: QAClass, assets: [DKAsset], completion: ([PhotoClass]) -> Void) {

var imageCellHolder = [PhotoClass]()

for x in assets
{

x.fetchOriginalImage(completeBlock: { (image, info) in

let compressedImage = image?.resizeWithWidth(width: 800)

let imageData:Data = compressedImage!.jpegData(compressionQuality: 0.5)!

imageCellHolder.append(PhotoClass(job: String(self.selectedCommunity! + self.selectedLot!), photo: imageData, itemId: qa.itemId))

})
}

completion(imageCellHolder)
}

这里是循环完成时它应该调用的方法:

func loopFinished(imageCellHolder: [PhotoClass])
{
self.saveQAPhotos(cellHolder: imageCellHolder) { result in

print(result)

}
}

这就是我调用循环方法的方式:

self.loopImages(qa: qa, assets: assets, completion: self.loopFinished)

我的问题是在循环完成之前调用了完成处理程序方法 (loopFinished)。

如果您想知道,fetchOriginalImage 来自库 DKImagePickerController https://github.com/zhangao0086/DKImagePickerController

最佳答案

您需要一个 DispatchGroup 来完成多个非连续任务 finish completion

func loopImages(qa: QAClass, assets: [DKAsset], completion: ([PhotoClass]) -> Void) {

var imageCellHolder = [PhotoClass]()

let dispa = DispatchGroup()

for x in assets
{
dispa.enter()

x.fetchOriginalImage(completeBlock: { (image, info) in

let compressedImage = image?.resizeWithWidth(width: 800)

let imageData:Data = compressedImage!.jpegData(compressionQuality: 0.5)!

imageCellHolder.append(PhotoClass(job: String(self.selectedCommunity! + self.selectedLot!), photo: imageData, itemId: qa.itemId))

dispa.leave()

})
}

dispa.notify(queue: .main) {
completion(imageCellHolder)
}

}

关于ios - 循环的 Swift 4 完成处理程序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55004414/

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