Search code examples
iosimageswitch-statementsmsattachment

Unable to attach image to in-app SMS


I have a simple app that takes partial screenshot and then SMS the resultant image.

The image attached to the SMS in the pop-up SMS dialogue window is not the image I captured via screenshot - it's a 'blank' image.

Here's my code:

@IBAction func smsScreenShot(sender: AnyObject) {

    // Declare the snapshot boundaries

    let top: CGFloat = 100
    let bottom: CGFloat = 60

    // The size of the cropped image
    let size = CGSize(width: view.frame.size.width, height: view.frame.size.height - top - bottom)

    // Start the context
    UIGraphicsBeginImageContext(size)

    // use context in a couple of places
    let context = UIGraphicsGetCurrentContext()!

    // Transform the context so that anything drawn into it is displaced "top" pixels up
    CGContextTranslateCTM(context, 0, -top)

    // Draw the view into the context (this is the snapshot)
    view.layer.renderInContext(context)

    let snapshot = UIGraphicsGetImageFromCurrentImageContext()

    // End the context (this is required to not leak resources)
    UIGraphicsEndImageContext()


    // Composing the SMS
    if !MFMessageComposeViewController.canSendText() {
        print("SMS services are not available")
    }

    if (MFMessageComposeViewController.canSendText()) {

        let composeVC = MFMessageComposeViewController()
        composeVC.messageComposeDelegate = self

        composeVC.recipients = []
        composeVC.body = "Have a look at this image!!";

        // Attaching the image to the SMS.
        let image = snapshot
        let imageData = UIImagePNGRepresentation(image)
        composeVC.addAttachmentData(imageData!, typeIdentifier: "image/png", filename:"my image")
        self.presentViewController(composeVC, animated: true, completion: nil)

    }
}

I have researched this for hours and don't see where I am going wrong.

I have the identical code for adding the attachment to an in-app email, with obvious differences in the controllers, and it works fine. Just not working with regards to in-app SMS.

Thanks!


Solution

  • Change this line:-

    composeVC.addAttachmentData(imageData!, typeIdentifier: "image/png", filename:"my image")
    

    to this:-

     composeVC.addAttachmentData(imageData!, typeIdentifier: "image/png", filename:"myimage.png")
    

    There you go!