I’m designing an app that allows a user to email themselves data from the application. The problem i’m running into is that when i use addAttachmentData, it takes an insane amount of time to load. When I remove the addAttachmentData and just make it a regular email, it loads instantly.
The data I’m parsing out isn’t that large. Its just two csvs with 2×3 and 30×1 arrays. I’m simulating it on my personal iphone 15 pro max as well.
This is the code. maybe I’m doing something wrong? How does it take so long for the email to load with attachments
import SwiftUI
import MessageUI
struct EmailComposer: UIViewControllerRepresentable {
@Environment(.presentationMode) var presentationMode
let fileURLs: [URL]
let subject: String
let messageBody: String
let isHTML: Bool
class Coordinator: NSObject, MFMailComposeViewControllerDelegate {
var parent: EmailComposer
init(_ parent: EmailComposer) {
self.parent = parent
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true) {
self.parent.presentationMode.wrappedValue.dismiss()
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> MFMailComposeViewController {
let mailComposer = MFMailComposeViewController()
mailComposer.mailComposeDelegate = context.coordinator
mailComposer.setSubject(subject)
mailComposer.setMessageBody(messageBody, isHTML: isHTML)
DispatchQueue.global(qos: .userInitiated).async {
if MFMailComposeViewController.canSendMail() {
for fileURL in fileURLs {
if let fileData = try? Data(contentsOf: fileURL) {
mailComposer.addAttachmentData(fileData, mimeType: "text/csv", fileName: fileURL.lastPathComponent)
} else {
print("Cannot read file: (fileURL.lastPathComponent)")
}
}
DispatchQueue.main.async {
context.coordinator.parent.presentationMode.wrappedValue.dismiss()
}
} else {
print("Cannot send mail")
}
}
return mailComposer
}
func updateUIViewController(_ uiViewController: MFMailComposeViewController, context: Context) {
// No need to update the UIViewController in this case
}
}