Search code examples
swiftuiuiimagexcode12

SwiftUI 2.0: export group of images with .fileExporter modifier


This is a follow up on this thread: SwiftUI 2.0: export images with .fileExporter modifier

Goal: export a group of images in SwiftUI

What I did: I am using the .fileExporter modifier, with the FileDocument struct. Also open to other approach, like . fileMover modifier for example.

Problem: When setting the FileDocument for multiple images struct I am getting am error on func fileWrapper (check code bellow).

Question: How can I export multiple images in SwiftUI (could be any method)?

    //file exporter
    .fileExporter(isPresented: $exportFile, document: ImageDocument(
                    
                    
                    image: UIImage(data: product.cover ?? Data())!,
                    image2:  UIImage(data: product.cover2 ?? Data())!)
                  
                  ,
           
contentType: .jpeg, onCompletion: { (result) in
            if case .success = result {
                
                print("Success")
            } else {
                print("Failure")
            }
        })
//export group of images
struct ImageDocument: FileDocument {
    
    static var readableContentTypes: [UTType] { [.jpeg] }

    var image: UIImage
    var image2: UIImage


    init(
        image: UIImage?,
        image2: UIImage?
    ) {
        
        self.image = image ?? UIImage()
        self.image2 = image2 ?? UIImage()

    }
    


    init(configuration: ReadConfiguration) throws {
        guard let data = configuration.file.regularFileContents,
              let image = UIImage(data: data),
              let image2 = UIImage(data: data)

        else {
            throw CocoaError(.fileReadCorruptFile)
        }
        self.image = image
        self.image2 = image2

    }

    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
        return FileWrapper(regularFileWithContents:
                            image.jpegData(compressionQuality: 0.80)!,
                            image2.jpegData(compressionQuality: 0.80)!//<----- getting an "extra argument error here
                            )
    }
    
}

Update: Tried to rewrite Max answer to UIImage, but this only exports 1 image:


import SwiftUI

class AppContext: ObservableObject {
    @Published var fileSaveDialogShown = false
}

@main
struct FocalApp: App {
  @StateObject var appContext = AppContext()

  var body: some Scene {
    WindowGroup {
      ContentView()
        .environmentObject(self.appContext)
        .fileExporter(
          isPresented: $appContext.fileSaveDialogShown,
          documents: [
            ImageDocument(image: UIImage(named: "1")),
            ImageDocument(image: UIImage(named: "2"))
          ],
          contentType: .jpeg // Match this to your representation in ImageDocument
        ) { url in
          print("Saved to", url) // [URL]
        }
    }
  }
}

import SwiftUI
import UniformTypeIdentifiers

struct ImageDocument: FileDocument {
  static var readableContentTypes: [UTType] { [.jpeg, .png, .tiff] }

  var image: UIImage

  init(image: UIImage?) {
    self.image = image ?? UIImage()
  }

  init(configuration: ReadConfiguration) throws {
    guard let data = configuration.file.regularFileContents,
          let image = UIImage(data: data)
    else {
      throw CocoaError(.fileReadCorruptFile)
    }
    self.image = image
  }

  func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
    // You can replace tiff representation with what you want to export
    return FileWrapper(regularFileWithContents: image.jpegData(compressionQuality: 1)!)
  }
}


struct ContentView: View {
    
    @EnvironmentObject var appContext: AppContext
    
    var body: some View {
        VStack {
            Button(action: {
                appContext.fileSaveDialogShown.toggle()
            }, label: {
                Text("Button")
            })
        }
        .frame(width: 200, height: 200)
    }
}



Solution

  • You need to use fileExporter with documents instead of document, which takes in a Collection

    Here's how I'm doing it on macOS, adapting it should be straightforward:

    import SwiftUI
    import UniformTypeIdentifiers
    
    struct ImageDocument: FileDocument {
      static var readableContentTypes: [UTType] { [.jpeg, .png, .tiff] }
    
      var image: NSImage
    
      init(image: NSImage?) {
        self.image = image ?? NSImage()
      }
    
      init(configuration: ReadConfiguration) throws {
        guard let data = configuration.file.regularFileContents,
              let image = NSImage(data: data)
        else {
          throw CocoaError(.fileReadCorruptFile)
        }
        self.image = image
      }
    
      func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
        // You can replace tiff representation with what you want to export
        return FileWrapper(regularFileWithContents: image.tiffRepresentation!)
      }
    }
    
    @main
    struct FocalApp: App {
      @StateObject var appContext = AppContext()
    
      var body: some Scene {
        WindowGroup {
          MainView()
            .environmentObject(self.appContext)
            .fileExporter(
              isPresented: $appContext.fileSaveDialogShown,
              documents: [
                ImageDocument(image: NSImage(named: "testimage1")),
                ImageDocument(image: NSImage(named: "testimage2"))
              ],
              contentType: .tiff // Match this to your representation in ImageDocument
            ) { url in
              print("Saved to", url) // [URL]
            }
        }
      }
    }