0

I would like for user to choose their desired image from photo gallery and then that image is included in the email that they're are about to send.

I've already created a button that enables user to open gallery and then after choosing image it is displayed in UIImageView. However, my code that I have written in addAttachment I think is incorrect.

The UIImageViews name is imageView

button to open gallery

@IBAction func openPhotoLibraryButton(sender: AnyObject) {
    if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary;
        imagePicker.allowsEditing = true
        self.present(imagePicker, animated: true, completion: nil)
    }
}

Email code

@IBAction func sendEmail(_ sender: Any) {
    if MFMailComposeViewController.canSendMail() {
        let mail = MFMailComposeViewController()
        let emailFullName: String = fullName.text!
        let emailCell: String = cellNumber.text!
        let image1: UIImage = imageView.image!
        mail.mailComposeDelegate = self
        //Reciepient
        mail.setToRecipients(["kondja99@gmail.com"])
        // Email body
        mail.setMessageBody("FullName: \(emailFullName) \n Cellphone No: \(emailCell)"   , isHTML: false)
        // Subject
        mail.setSubject("Application for RTO: ")
        
        // Email attachment
        mail.addAttachmentData(Data, mimeType: "image/jpg", fileName: "\(image1)")
        self.present(mail, animated: true, completion: nil)
        }
     else {
        print("Email cannot be sent")
        
    }
}
Sindano
  • 11
  • 1
  • 4
  • `mail.addAttachmentData(Data, mimeType: "image/jpg", fileName: "\(image1)")` `Data`, that's the class name, no? It doesn't compilee? Where/How do you retrieve the save image? – Larme Jun 10 '22 at 15:56
  • When you get an image from the picker, save it in a variable. Then instead of Data use image.pngData() (assuming you have the UImage type). – Asteroid Jun 10 '22 at 15:58
  • It should be somethinig like: `if let imageData =. image1.jpegData(compressionQuality: 1) { mail.addAttachmentData(imageData, mimeType: "image/jpg", fileName: "image") } else { print("Couldn't get image data") }` – Larme Jun 10 '22 at 15:59
  • @Larme, yes this code works, I did make a mistake with my code, yours solved the problem. – Sindano Jun 10 '22 at 16:52
  • @Larme how does one go about adding another image to the email so that they are 2, I found that I can't add another image due to the UIImagePickerController(), I can only create one variable using the UIImagePickerController(). – Sindano Jun 11 '22 at 15:43
  • That's another issue related to `UIImagePickerController`, A quick search: https://stackoverflow.com/questions/20756899/how-to-select-multiple-images-from-uiimagepickercontroller etc. – Larme Jun 12 '22 at 18:01

0 Answers0