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
completion(str)
}
}
private func dataContents() -> String { //<--- called from the FileWrapper()
self.contents() {
self.data = $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
...
...
}