How can I grab a pdf file from the files app in SwiftUI and import it into my app on an iPhone with iOS

Viewed 1181

I would like to be able to import pdf files from the Files app to my app and not sure how to achieve this.

Is there a FilePicker or something like that which I can use for a similar behavior to the apple Mail app when you add an attachment to an email? With mail app when you press "add document" it opens a document browser that you can select a file. I believe this is from iCloud Drive.

1 Answers

You can use .fileImporter in SwiftUI:

struct ContentView : View {
    @State private var presentImporter = false
    
    var body: some View {
        Button("Open") {
            presentImporter = true
        }.fileImporter(isPresented: $presentImporter, allowedContentTypes: [.pdf]) { result in
            switch result {
            case .success(let url):
                print(url)
                //use `url.startAccessingSecurityScopedResource()` if you are going to read the data
            case .failure(let error):
                print(error)
            }
        }
    }
}
Related