0

I use PHPickerViewController to select up to 5 photos from device photo library, then i need to map it to another object and compress each photo size to 10MB max, but my compression methods cause a big ui lagging and scroll blocking. I've tried to send this task to another thread, but it didn't help a lot.

View:

struct SupportRequestView: View {
  @State var attachments: [Attachment] = []
  @State var attachmentsImp: [AttachmentFileImp] = []

  var body: some View {
    VStack {
       List {
     // my ui here
     }
    }
     .sheet(isPresented: $showImagePicker) {
      PhotoPicker(images: $attachments, ready: $readyToProceedAttachments, selectionLimit: 5)
    }
    .onChange(of: attachments, perform: { attachments in
      Task.detached(priority: .background) {
        await mapAttachements(attachements: attachments)
      }
    })

  // MARK: - Private Methods
  private func mapAttachements(attachements: [Attachment]) async {
    self.attachmentsImp = attachments.map({
      AttachmentFileImp(
        name: $0.name,
        data: compress(image: $0.image, toSize: 10000000) // 10MB
      )
    })
  }

  private func compress(image: UIImage, toSize: Int64) -> Data {
    guard let data = image.pngData() else { return Data() }
    let emptyData = Data()
    if data.count >= toSize {
      guard let mediumQaulity = image.jpeg(.medium) else { return emptyData }
      if mediumQaulity.count >= toSize {
        guard let lowQaulity = image.jpeg(.low) else { return emptyData }
        if lowQaulity.count >= toSize {
          return emptyData
        } else { return lowQaulity }
      } else { return mediumQaulity }
    } else { return data }
  }
}
mpotapov
  • 23
  • 5

0 Answers0