diff --git a/Modules/Sources/Browse/UI/Components/DocumentPicker.swift b/Modules/Sources/Browse/UI/Components/DocumentPicker.swift new file mode 100644 index 0000000..b7b1188 --- /dev/null +++ b/Modules/Sources/Browse/UI/Components/DocumentPicker.swift @@ -0,0 +1,91 @@ +// +// DocumentPicker.swift +// Browse +// +// Created by Javier Cicchelli on 17/12/2022. +// Copyright © 2022 Röck+Cöde. All rights reserved. +// + +import Foundation +import SwiftUI +import UIKit + +struct DocumentPicker: UIViewControllerRepresentable { + + // MARK: Type aliases + + typealias SelectedClosure = ([URL]) -> Void + typealias CancelledClosure = () -> Void + + // MARK: Properties + + private let selected: SelectedClosure + private let cancelled: CancelledClosure? + + // MARK: Initialisers + + init( + selected: @escaping SelectedClosure, + cancelled: CancelledClosure? = nil + ) { + self.selected = selected + self.cancelled = cancelled + } + + // MARK: Functions + + func makeUIViewController(context: Context) -> UIDocumentPickerViewController { + let controller = UIDocumentPickerViewController( + forOpeningContentTypes: [.item], + asCopy: true + ) + + controller.allowsMultipleSelection = false + controller.shouldShowFileExtensions = false + controller.delegate = context.coordinator + + return controller + } + + func updateUIViewController( + _ uiViewController: UIDocumentPickerViewController, + context: Context + ) { } + + func makeCoordinator() -> Coordinator { + .init(self) + } +} + +// MARK: - Coordinators + +extension DocumentPicker { + class Coordinator: NSObject, UIDocumentPickerDelegate { + + // MARK: Properties + + private var parent: DocumentPicker + + // MARK: Initialisers + + init(_ parent: DocumentPicker) { + self.parent = parent + } + + // MARK: UIDocumentPickerDelegate + + func documentPicker( + _ controller: UIDocumentPickerViewController, + didPickDocumentsAt urls: [URL] + ) { + parent.selected(urls) + } + + func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { + controller.dismiss(animated: true) { [weak self] in + self?.parent.cancelled?() + } + } + + } +}