I have the QR Code generator working, it display image to my qrImageView
UIImageView
.
Now, what I want to do is attach that QR Code image to email. Tried the code specified below but I get an error "found nil while unwrapping an Optional value".
Please help!
Function for generating QR CODE
func generateQRCode(from string:String) -> UIImage? {
let data = string.data(using: String.Encoding.isoLatin1)
if let filter = CIFilter(name:"CIQRCodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 100, y: 100)
if let output = filter.outputImage?.applying(transform) {
return UIImage(ciImage: output)
}
}
return nil
}
@IBAction func generateAction(_ sender: Any) {
if let actualText = qrCodeTextField.text {
let image = generateQRCode(from: actualText)
qrImageView.image = image
}
}
Code for attaching QR Code to Email
func configureMailController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["tsm@yahoo.com"])
mailComposerVC.setSubject("\(subject) QR Code")
mailComposerVC.setMessageBody("Please see attached QR Code", isHTML: false)
//Add Image as Attachment
if let image = qrImageView.image {
let data: NSData = UIImagePNGRepresentation(image)! as NSData
mailComposerVC.addAttachmentData(data as Data, mimeType: "image/png", fileName: "image")
}
return mailComposerVC
}
This works for me. I have to convert the CIImage first to UIImage so that the QRCode can be attached to email
func convert(cmage:CIImage) -> UIImage
{
let context:CIContext = CIContext.init(options: nil)
let cgImage:CGImage = context.createCGImage(cmage, from: cmage.extent)!
let image:UIImage = UIImage.init(cgImage: cgImage)
return image
}