BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

Document Picker

Forums > SwiftUI

My first attempt to prompt user for, and read in a text file. Does not request a file. I have entered the usage descriptions for Privacy Documents, desktop and downloads in the info tab. Is there a different Privacy setting I need perhaps?

import SwiftUI
import MobileCoreServices
import UniformTypeIdentifiers

struct FileImporterView: UIViewControllerRepresentable {
    @Binding var fileURL: URL?
    @Environment(\.presentationMode) var presentationMode

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
        let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.commaSeparatedText])
        picker.allowsMultipleSelection = false
        picker.delegate = context.coordinator
        return picker
    }

    func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {
        // No update needed
    }

    class Coordinator: NSObject, UIDocumentPickerDelegate {
        let parent: FileImporterView

        init(_ parent: FileImporterView) {
            self.parent = parent
        }

        func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
            parent.fileURL = urls.first
            parent.presentationMode.wrappedValue.dismiss()
        }

        func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
            parent.presentationMode.wrappedValue.dismiss()
        }
    }
}

struct ImportSkippers: View {
    @State private var fileURL: URL?

    var body: some View {
        VStack {
            Text("Selected File: \(fileURL?.lastPathComponent ?? "None")")

            Button("Import Text File") {
                fileURL = URL(string: "start") // Reset fileURL

                let fileImporter = FileImporterView(fileURL: $fileURL)
                print(fileURL)
                fileImporter.edgesIgnoringSafeArea(.all)
            }
        }
        .padding()
    }
}

2      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.