2022-12-17 11:48:25 +01:00
|
|
|
//
|
2022-12-18 00:58:29 +01:00
|
|
|
// SelectDocumentPicker.swift
|
2022-12-17 11:48:25 +01:00
|
|
|
// Browse
|
|
|
|
//
|
|
|
|
// Created by Javier Cicchelli on 17/12/2022.
|
|
|
|
// Copyright © 2022 Röck+Cöde. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import SwiftUI
|
|
|
|
import UIKit
|
|
|
|
|
2022-12-18 00:58:29 +01:00
|
|
|
struct SelectDocumentPicker: UIViewControllerRepresentable {
|
2022-12-17 11:48:25 +01:00
|
|
|
|
|
|
|
// 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)
|
|
|
|
}
|
2022-12-18 00:58:29 +01:00
|
|
|
|
2022-12-17 11:48:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: - Coordinators
|
|
|
|
|
2022-12-18 00:58:29 +01:00
|
|
|
extension SelectDocumentPicker {
|
2022-12-17 11:48:25 +01:00
|
|
|
class Coordinator: NSObject, UIDocumentPickerDelegate {
|
|
|
|
|
|
|
|
// MARK: Properties
|
|
|
|
|
2022-12-18 00:58:29 +01:00
|
|
|
private var parent: SelectDocumentPicker
|
2022-12-17 11:48:25 +01:00
|
|
|
|
|
|
|
// MARK: Initialisers
|
|
|
|
|
2022-12-18 00:58:29 +01:00
|
|
|
init(_ parent: SelectDocumentPicker) {
|
2022-12-17 11:48:25 +01:00
|
|
|
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?()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|