UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

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.