Skip to content

Instantly share code, notes, and snippets.

@richo
Created July 10, 2019 05:50
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richo/61f308f5e4ba1fe7eefb8035aaa7817a to your computer and use it in GitHub Desktop.
Save richo/61f308f5e4ba1fe7eefb8035aaa7817a to your computer and use it in GitHub Desktop.
//
// FilePickerPresentedView.swift
// flysight-grapher
//
// Created by richö butts on 7/8/19.
// Copyright © 2019 richö butts. All rights reserved.
//
import Foundation
import SwiftUI
import MobileCoreServices
struct FilePickerController: UIViewControllerRepresentable {
var callback: (URL) -> ()
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: UIViewControllerRepresentableContext<FilePickerController>) {
// Update the controller
}
func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
print("Making the picker")
let controller = UIDocumentPickerViewController(documentTypes: [String(kUTTypeText)], in: .open)
controller.delegate = context.coordinator
print("Setup the delegate \(context.coordinator)")
return controller
}
class Coordinator: NSObject, UIDocumentPickerDelegate {
var parent: FilePickerController
init(_ pickerController: FilePickerController) {
self.parent = pickerController
print("Setup a parent")
print("Callback: \(parent.callback)")
}
func documentPicker(didPickDocumentsAt: [URL]) {
print("Selected a document: \(didPickDocumentsAt[0])")
parent.callback(didPickDocumentsAt[0])
}
func documentPickerWasCancelled() {
print("Document picker was thrown away :(")
}
deinit {
print("Coordinator going away")
}
}
}
struct PickerView: View {
var callback: (URL) -> ()
var body: some View {
FilePickerController(callback: callback)
}
}
#if DEBUG
struct PickerView_Preview: PreviewProvider {
static var previews: some View {
func filePicked(_ url: URL) {
print("Filename: \(url)")
}
return PickerView(callback: filePicked)
.aspectRatio(3/2, contentMode: .fit)
}
}
#endif
@OscarGorog
Copy link

Correct methods:

documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL])
documentPickerWasCancelled(_ controller: UIDocumentPickerViewController)

@richo
Copy link
Author

richo commented May 20, 2020

@OscarGorog thanks! Are these different for iOS and Catalyst? From memory it works in one place but not the other.

@OscarGorog
Copy link

OscarGorog commented May 20, 2020

Hmmm... all I know is that the methods weren't being called so I checked the methods and they were different...

@richo
Copy link
Author

richo commented May 20, 2020

Gotcha, that also sounds like my experience. Thanks for posting the solution!

@OscarGorog
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment