diff --git a/ElementX/Sources/Screens/MediaPickerScreen/PhotoLibraryPicker.swift b/ElementX/Sources/Screens/MediaPickerScreen/PhotoLibraryPicker.swift index 5bbb5eeb7..2812bb810 100644 --- a/ElementX/Sources/Screens/MediaPickerScreen/PhotoLibraryPicker.swift +++ b/ElementX/Sources/Screens/MediaPickerScreen/PhotoLibraryPicker.swift @@ -34,7 +34,7 @@ struct PhotoLibraryPicker: UIViewControllerRepresentable { func makeUIViewController(context: Context) -> PHPickerViewController { var configuration = PHPickerConfiguration(photoLibrary: .shared()) - + configuration.selection = .ordered configuration.selectionLimit = switch selectionType { case .single: 1 @@ -86,18 +86,21 @@ struct PhotoLibraryPicker: UIViewControllerRepresentable { Task { let selectedURLs = await withTaskGroup { taskGroup in - for result in results { - taskGroup.addTask { await self.processResult(result) } - } - - var selectedURLs = [URL]() - for await url in taskGroup { - if let url { - selectedURLs.append(url) + for (index, result) in results.enumerated() { + taskGroup.addTask { + let url = await self.processResult(result) + return (index, url) } } - return selectedURLs + var selectedURLs = [URL?](repeating: nil, count: results.count) + for await (index, url) in taskGroup { + if let url { + selectedURLs[index] = url + } + } + + return selectedURLs.compactMap { $0 } } photoLibraryPicker.callback(.selectedMediaAtURLs(selectedURLs)) diff --git a/ElementX/Sources/Services/Media/MediaUploadingPreprocessor.swift b/ElementX/Sources/Services/Media/MediaUploadingPreprocessor.swift index a408fb77d..459e561d6 100644 --- a/ElementX/Sources/Services/Media/MediaUploadingPreprocessor.swift +++ b/ElementX/Sources/Services/Media/MediaUploadingPreprocessor.swift @@ -101,23 +101,26 @@ struct MediaUploadingPreprocessor { /// and its associated details or any resulting error func processMedia(at urls: [URL], maxUploadSize: UInt) async -> Result<[MediaInfo], MediaUploadingPreprocessorError> { await withTaskGroup { taskGroup in - for url in urls { + for (index, url) in urls.enumerated() { taskGroup.addTask { - await processMedia(at: url, maxUploadSize: maxUploadSize) + let result = await processMedia(at: url, maxUploadSize: maxUploadSize) + return (index, result) } } - var mediaInfos = [MediaInfo]() - for await result in taskGroup { + // Store results in their respective index as they come in + var results = [MediaInfo?](repeating: nil, count: urls.count) + + for await (index, result) in taskGroup { switch result { case .success(let mediaInfo): - mediaInfos.append(mediaInfo) + results[index] = mediaInfo case .failure(let error): return .failure(error) } } - return .success(mediaInfos) + return .success(results.compactMap { $0 }) } }