another.im-ios/ConversationsClassic/View/Main/Conversation/Attachments/FilesPickerView.swift
fmodf b3b3b3aef7 mv-experiment (#1)
Reviewed-on: narayana/conversations-classic-ios#1
Co-authored-by: fmodf <fmodf.ios@gmail.com>
Co-committed-by: fmodf <fmodf.ios@gmail.com>
2024-09-03 15:13:58 +00:00

66 lines
2.1 KiB
Swift

import SwiftUI
import UIKit
struct FilesPickerView: View {
@Environment(\.router) var router
@EnvironmentObject var attachments: AttachmentsStore
var body: some View {
DocumentPicker(
completion: { dataArray, extensionsArray in
attachments.sendDocuments(dataArray, extensionsArray)
router.dismissEnvironment()
},
cancel: {
router.dismissEnvironment()
}
)
}
}
struct DocumentPicker: UIViewControllerRepresentable {
let completion: ([Data], [String]) -> Void
let cancel: () -> Void
func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentPicker>) -> UIDocumentPickerViewController {
let picker: UIDocumentPickerViewController
picker = UIDocumentPickerViewController(forOpeningContentTypes: [.item], asCopy: true)
picker.delegate = context.coordinator
picker.allowsMultipleSelection = true
return picker
}
func updateUIViewController(_: UIDocumentPickerViewController, context _: UIViewControllerRepresentableContext<DocumentPicker>) {}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UIDocumentPickerDelegate {
var parent: DocumentPicker
init(_ parent: DocumentPicker) {
self.parent = parent
}
func documentPicker(_: UIDocumentPickerViewController, didPickDocumentsAt: [URL]) {
var dataArray = [Data]()
var extensionArray = [String]()
for url in didPickDocumentsAt {
do {
let data = try Data(contentsOf: url)
dataArray.append(data)
extensionArray.append(url.pathExtension)
} catch {
print("Unable to load data from \(url): \(error)")
}
}
parent.completion(dataArray, extensionArray)
}
func documentPickerWasCancelled(_: UIDocumentPickerViewController) {
parent.cancel()
}
}
}