I'm building an app in which I need to attach and send multiple photos in an email. To accomplish this I save the photos to disk in the camera VC and access them in the viewDidLoad() of the email VC. I store them as .pngData() in a array and attach them in the MFMailComposeViewController using this code:
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients([UserDefaults.standard.string(forKey: "Email")!])
mailComposerVC.setSubject("Заявление")
mailComposerVC.setMessageBody("\(ProtocolText.text!)", isHTML: false)
// unpacking images from array and attaching them to Email
var dataName = 0
for data in imageData {
dataName += 1
mailComposerVC.addAttachmentData(data, mimeType: "image/png", fileName: "\(dataName).png")
}
return mailComposerVC
}
These are my "save" and "get" methods:
func loadImage(fileName: String) -> UIImage? {
let documentDirectory = FileManager.SearchPathDirectory.documentDirectory
let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)
if let dirPath = paths.first {
let imageUrl = URL(fileURLWithPath: dirPath).appendingPathComponent(fileName)
let image = UIImage(contentsOfFile: imageUrl.path)
return image
}
return nil
}
// Used in CameraViewController
func saveImage(imageName: String, image: UIImage) {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileName = imageName
let fileURL = documentsDirectory.appendingPathComponent(fileName)
guard let data = image.jpegData(compressionQuality: 1) else { return }
//Checks if file exists, removes it if so.
if FileManager.default.fileExists(atPath: fileURL.path) {
do {
try FileManager.default.removeItem(atPath: fileURL.path)
print("Removed old image")
} catch let removeError {
print("couldn't remove file at path", removeError)
}
}
do {
try data.write(to: fileURL)
} catch let error {
print("error saving file with error", error)
}
}
For some reason the images attach but the email takes at least 15 seconds to send. The "send" button just gets stuck. I don't know why. Please help.
It was a problem with the weight of the image. One image used to weigh 6848.7939453125 KB. Since I had multiple images it took a lot of time to process them. Compressing them using the image.jpegData(compressionQuality: CGFloat)!)
method solved all problems. Thank you Mark Thormann for suggesting the fix!