Return value from an async thread in SwiftUI to use with fileExporter

I am trying to return some data that is fetched from a database asynchronously to export to a CSV file. I am using the new SwiftUI .fileExporter which requires to implement FileWrapper() which is part of FileDocument. The problem is that I am not able to return the result to the FileWrapper(regularFileWithContents: Data) I am using a completion handler but the issue is it is returning before populating the values. There are a number of posts online, but does not seem to work for me (I know I am missing something). Any help would be great.

Here is what I have done so far:

The Document structure required for .fileExporter():

    struct DataDocument: FileDocument {
        static var readableContentTypes: [UTType] {[.plainText]}
        @State private var data = "" // String data that is obtained from database. contents() method below fetches the data. I do have a completion handler
        init(configuration: ReadConfiguration) throws {
            data = ""

// this is where I am having trouble....
    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
        return FileWrapper(regularFileWithContents: dataContents().data(using: .utf8)!) //<--- wrapper being called by .fileExporter
    private func contents(completion: @escaping(String) -> Void) { //<-- method to fetch data from database
        DispatchQueue.main.async {
           let str = getData().toString() //<--- data obtained from database
    private func dataContents() -> String { //<--- called from the FileWrapper()
        self.contents() {
   = $0
        return data //<---- This returns empty string and I do know that it is immediately returning. this is where I need your help to return after the data is being set

FIleExporter called from ContentView

.fileExporter(isPresented: $isExporting, document: DataDocument(), contentType: .plainText) { result in

Pushing to top. Any ideas on how to fix the above issue.

Thanks much!

You may have better luck asking over instead. Though I have an inkling thatif you want to asynchronously load the document, FileDocument may not be a good fit. ReferenceFileDocument might work better.

Thank you, will try that.

Terms of Service

Privacy Policy

Cookie Policy