42 lines
1.4 KiB
Swift
42 lines
1.4 KiB
Swift
import SwiftUI
|
|
import UniformTypeIdentifiers
|
|
|
|
struct DocumentPicker: UIViewControllerRepresentable {
|
|
let onPick: (URL) -> Void
|
|
let onCancel: () -> Void
|
|
|
|
func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
|
|
let types: [UTType] = [UTType(filenameExtension: "epub")].compactMap { $0 }
|
|
let controller = UIDocumentPickerViewController(forOpeningContentTypes: types, asCopy: true)
|
|
controller.allowsMultipleSelection = false
|
|
controller.delegate = context.coordinator
|
|
return controller
|
|
}
|
|
|
|
func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {
|
|
}
|
|
|
|
func makeCoordinator() -> Coordinator {
|
|
Coordinator(onPick: onPick, onCancel: onCancel)
|
|
}
|
|
|
|
final class Coordinator: NSObject, UIDocumentPickerDelegate {
|
|
private let onPick: (URL) -> Void
|
|
private let onCancel: () -> Void
|
|
|
|
init(onPick: @escaping (URL) -> Void, onCancel: @escaping () -> Void) {
|
|
self.onPick = onPick
|
|
self.onCancel = onCancel
|
|
}
|
|
|
|
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
|
|
guard let url = urls.first else { return }
|
|
onPick(url)
|
|
}
|
|
|
|
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
|
|
onCancel()
|
|
}
|
|
}
|
|
}
|