我正在使用iOS 14中新的图像拾取器API,并且希望能够在调用底部的代码之前完成对图像的for循环处理,这将更新我的数据源,最后重新加载集合视图的数据。目前,底部的代码甚至在totalConversionsCompleted达到1之前就被调用了。
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
dismiss(animated: true, completion: nil)
var selectedImageDatas = [Data?](repeating: nil, count: results.count) // Awkwardly named, sure
var totalConversionsCompleted = 0
for (index, result) in results.enumerated() {
result.itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.image.identifier) { (url, error) in
guard let url = url else {
totalConversionsCompleted += 1
return
}
let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let source = CGImageSourceCreateWithURL(url as CFURL, sourceOptions) else {
totalConversionsCompleted += 1
return
}
let downsampleOptions = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: 2_000,
] as CFDictionary
guard let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, downsampleOptions) else {
totalConversionsCompleted += 1
return
}
let data = NSMutableData()
guard let imageDestination = CGImageDestinationCreateWithData(data, kUTTypeJPEG, 1, nil) else {
totalConversionsCompleted += 1
return
}
// Don't compress PNGs, they're too pretty
let isPNG: Bool = {
guard let utType = cgImage.utType else { return false }
return (utType as String) == UTType.png.identifier
}()
let destinationProperties = [
kCGImageDestinationLossyCompressionQuality: isPNG ? 1.0 : 0.75
] as CFDictionary
CGImageDestinationAddImage(imageDestination, cgImage, destinationProperties)
CGImageDestinationFinalize(imageDestination)
selectedImageDatas[index] = data as Data
totalConversionsCompleted += 1
}
}
//I want to wait for the processing of images and then do this
self.images.append(contentsOf: selectedImageDatas)
RxBus.shared.post(event: Events.AlbumUpdated(images: self.images, indexPath: self.selectedIndexPath))
self.collectionView.reloadData()
}发布于 2020-09-27 19:13:56
let g = DispatchGroup()
for (index, result) in results.enumerated() {
g.enter()
result.itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.image.identifier) { (url, error) in
...
g.leave()
}
}
g.notify(queue: .main) {
// completed here
}https://stackoverflow.com/questions/64084968
复制相似问题