Пожалуйста, найдите код ниже.
- Я создаю QRCode.
- Затем я хочу преобразовать его в png и отправить по электронной почте в виде вложения.
Строка:
let imgData = UIImagePNGRepresentation(imageToEmail)
продолжает возвращать nil
и вызываеткод для сбоя.Любая помощь?
class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
@IBOutlet weak var dataField: UITextField!
@IBOutlet weak var displayCodeView: UIImageView!
var filter:CIFilter!
var qrImage = UIImage()
@IBAction func generatePressed(_ sender: UIButton) {
if let text = dataField.text {
let data = text.data(using: .ascii, allowLossyConversion: false)
filter = CIFilter(name: "CIQRCodeGenerator")
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 10, y: 10)
qrImage = UIImage(ciImage: filter.outputImage!.transformed(by: transform))
displayCodeView.image = qrImage
let mailComposeViewController = configureMailController(imageToEmail: qrImage)
if MFMailComposeViewController.canSendMail() {
self.present(mailComposeViewController, animated: true, completion: nil)
} else {
showMailError()
}
}
}
func configureMailController(imageToEmail: UIImage) -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["jc@project44laight.com"])
mailComposerVC.setSubject("QRCode")
let imgData = UIImagePNGRepresentation(imageToEmail)
mailComposerVC.addAttachmentData(imgData!, mimeType: "image/png", fileName: "qrCode.png")
let emailBody = "<html><body><p>QR code is attached in image </p></body></html>"
mailComposerVC.setMessageBody(emailBody, isHTML:true)
return mailComposerVC
}
func showMailError() {
let sendMailErrorAlert = UIAlertController(title: "Email error", message: "Your device could not send email", preferredStyle: .alert)
let dismiss = UIAlertAction(title: "Ok", style: .default, handler: nil)
sendMailErrorAlert.addAction(dismiss)
self.present(sendMailErrorAlert, animated: true, completion: nil)
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
switch result {
case .cancelled:
print("Mail cancelled")
break
case .saved:
print("Mail saved")
break
case .sent:
print("Mail sent")
break
case .failed:
print("Mail failed to send")
break
}
controller.dismiss(animated: true, completion: nil)
}
}