swiftmfmailcomposer

Swift MFMailComposer Optional Tag


I want to ask a question about MFMailComposer usage on Swift.

I am creating an email template below. It works. But, it puts "optional" tags before every label data. Can anyone help me? How can I trim that tag? Thanks!

I am sharing my screenshot below.

https://www.dropbox.com/s/mk23ze0p32769uj/IMG_4152.jpg?dl=0

and here is my code;

    @IBAction func sendEmailClicked(_ sender: AnyObject) {

    let dateString: String = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short)
    let body = "Lorem Ipsum <strong>\(dateString)</strong> dolor sit amet. <br><br><p><strong>\(String(describing: detailedLabel.text)).</strong></p><br>Lorem ipsum dolor sit amet.<br><br><p> <strong>\(String(describing: taskDescriptionTextView.text))</strong></p>"



    mailComposer = MFMailComposeViewController()
    mailComposer.mailComposeDelegate = self

    mailComposer.setToRecipients(["acme@acme.com"])
    mailComposer.setSubject("\(dateString) Lorem Ipsum dolor sit amet.")
    mailComposer.setMessageBody(body, isHTML: true)

    if let image = self.taskPhotoImageView.image {
        let imageData: Data = UIImagePNGRepresentation(image)!
            mailComposer.addAttachmentData(imageData, mimeType: "image/jpg", fileName: "image.jpg")
    }
    self.present(mailComposer, animated: true) {}
}

}


Solution

  • Your detailedLabel.text and taskDescriptionTextView.text are both optionals, you should unwrap them before you use them.

    guard let detailText = detailedLabel.text, let descriptionText = taskDescriptionTextView.text else {
        //error handling
        return
    }
    

    Now you can use them in your body string

    let body = "Lorem Ipsum <strong>\(dateString)</strong> dolor sit amet. <br><br><p><strong>\(detailText).</strong></p><br>Lorem ipsum dolor sit amet.<br><br><p> <strong>\(descriptionText)</strong></p>"