3

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!

Alex
  • 299
  • 3
  • 16
  • You are calling `addAttachmentData:typeIdentifier:filename:` incorrectly. Please read the documentation. `"png"` is not a valid UTI. – matt Dec 30 '15 at 21:03
  • try adding `as! UIImage` at the end of the PNGrepresentation. That may work better for you then – Julian E. Dec 31 '15 at 00:28

3 Answers3

4

Try it this way.

messageVC.addAttachmentData(
                             imageData, 
                             typeIdentifier: "public.data", 
                             filename: "image.png"
                            )
elp
  • 8,021
  • 7
  • 61
  • 120
dscrown
  • 578
  • 1
  • 5
  • 21
1

Solution for Swift 4.2/5

let imageData = image.pngData()
Michael
  • 748
  • 8
  • 11
0

The problem is with the value that is passed as 'filename' param in addAttachmentData function. It should have valid extension. i.e. if you provide png image data, value passed as 'filename' should be 'pic.png', not 'pic'. Also for the 'typeIdentifier' you should use kUTTypePNG value (defined in MobileCoreServices module) casted to String.

Jovan Stankovic
  • 4,661
  • 4
  • 27
  • 16