swiftuidocumentgroup

How to read large files using SwiftUI DocumentGroup without making a temporary copy?


I have made a SwiftUI DocumentApp that reads large media files but doesn't need to write them. In my document, I just want to store the file's URL, so that I can load it using e.g. AVAudioFile. I can't work out how to do this without creating a temporary copy of the file, as the author does here, because there is no way to the file URL from the fileWrapper

I have attempted to create a pipe using the configuration.file.regularFileContents (Data), but so far I had no success reading from that pipe.

  init(configuration: ReadConfiguration) throws {
    let tempURL = makeTemporaryFileURL()
    FileManager.default.createFile(atPath: tempURL.path, contents: configuration.file.regularFileContents, attributes: nil)
    audioFileUrl = tempURL
  }

Solution

  • You can get fileURL via document configuration, like

    @main
    struct MyApp: App {
        var body: some Scene {
            DocumentGroup(viewing: MyDocument.self) { fileConfig in
                // here fileConfig has `fileURL` of opened document, so 
                MyViewer(content: fileConfig.document, url: fileConfig.fileURL)
            }
        }
    }