diff --git a/ConversationsClassic/View/Screens/Attachments/AttachmentMediaPickerView.swift b/ConversationsClassic/View/Screens/Attachments/AttachmentMediaPickerView.swift index 7669fec..0851250 100644 --- a/ConversationsClassic/View/Screens/Attachments/AttachmentMediaPickerView.swift +++ b/ConversationsClassic/View/Screens/Attachments/AttachmentMediaPickerView.swift @@ -128,8 +128,9 @@ struct AttachmentMediaPickerView: View { } .clipped() .onTapGesture { - // TODO: Send selected media - print("Send media files") + let ids = selectedMedia.map { $0.id } + sendGalleryMedia(ids: ids) + store.dispatch(.conversationAction(.showAttachmentPicker(false))) } } .onAppear { @@ -166,14 +167,14 @@ struct AttachmentMediaPickerView: View { switch status { case .authorized, .limited: isGalleryAccessGranted = true - fetchImages() + fetchGallery() case .notDetermined: PHPhotoLibrary.requestAuthorization { status in DispatchQueue.main.async { self.isGalleryAccessGranted = status == .authorized if self.isGalleryAccessGranted { - self.fetchImages() + self.fetchGallery() } } } @@ -186,7 +187,7 @@ struct AttachmentMediaPickerView: View { } } - private func fetchImages() { + private func fetchGallery() { let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let assets = PHAsset.fetchAssets(with: fetchOptions) @@ -235,6 +236,58 @@ struct AttachmentMediaPickerView: View { } } } + + private func sendGalleryMedia(ids: [String]) { + var mediaData: [Data] = [] + let dispatchGroup = DispatchGroup() + + let asset = PHAsset.fetchAssets(withLocalIdentifiers: ids, options: nil) + asset.enumerateObjects { asset, _, _ in + dispatchGroup.enter() + if asset.mediaType == .image { + let manager = PHImageManager.default() + let option = PHImageRequestOptions() + option.isSynchronous = true + + manager.requestImage( + for: asset, + targetSize: PHImageManagerMaximumSize, + contentMode: .aspectFill, + options: option + ) { image, _ in + if let image { + let data = image.jpegData(compressionQuality: 1.0) ?? Data() + mediaData.append(data) + } + dispatchGroup.leave() + } + } else if asset.mediaType == .video { + let manager = PHImageManager.default() + let option = PHVideoRequestOptions() + option.version = .current + option.deliveryMode = .highQualityFormat + + manager.requestAVAsset(forVideo: asset, options: option) { avAsset, _, _ in + if let avAsset { + let url = (avAsset as? AVURLAsset)?.url + let data = try? Data(contentsOf: url ?? URL(fileURLWithPath: "")) + mediaData.append(data ?? Data()) + } + dispatchGroup.leave() + } + } + } + dispatchGroup.notify(queue: .main) { + store.dispatch(.conversationAction(.sendAttachment(.init( + id: UUID().uuidString, + type: .image, + url: nil, + data: mediaData, + str: nil, + localPath: nil + )))) + } + } } private struct ThumbnailView: Identifiable, View {