92 lines
2.1 KiB
Swift
92 lines
2.1 KiB
Swift
|
//
|
||
|
// 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?()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
}
|
||
|
}
|