Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift attaching image to iMessage

I'm trying to write a program that when you tap an image stored in the app, it opens up an iMessage with the image in the body ready to send. It is working except that the image appears in the text as a file with a name that you can open with Dropbox or some similar app. Is there a way to actually have the image be in the text, like when you text a photo from your library? Here is the code for my Message:

 func launchMessageComposeViewController(image: UIImage) {
        if MFMessageComposeViewController.canSendText() {
            let messageVC = MFMessageComposeViewController()
            messageVC.messageComposeDelegate = self
            var imageData = UIImagePNGRepresentation(image)
            messageVC.addAttachmentData(imageData!, typeIdentifier: "png", filename: "pic")
            self.presentViewController(messageVC, animated: true, completion: nil)
        }
        else {
            print("User hasn't setup Messages.app")
        }
    }

Thanks!

like image 450
Alex Avatar asked Nov 17 '25 08:11

Alex


2 Answers

Try it this way.

messageVC.addAttachmentData(
                             imageData, 
                             typeIdentifier: "public.data", 
                             filename: "image.png"
                            )
like image 161
dscrown Avatar answered Nov 19 '25 06:11

dscrown


Solution for Swift 4.2/5

let imageData = image.pngData()
like image 40
Michael Avatar answered Nov 19 '25 05:11

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!