Search code examples
iossmsscreenshotmms

Take screenshot and send it programmatically


When a user taps on a button in my app, I'd like to take a screenshot of the current view and open up a text message with that screenshot image as an attachment. How can I do this in iOS7?

(I've seen posts on how to take a screenshot but not anything on taking a screenshot and attaching it to a message)

Thanks!


Solution

  • 1. For taking a screenshot add the QuartzCore framework, you can use UIGraphicsBeginImageContextWithOptions

    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
    [self.myView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *theImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    NSData *theImageData=UIImageJPEGRepresentation(theImage, 1.0 ); //you can use PNG too
    

    2. For attaching this image in mail, add MessageUI framework in build phase. And use this NSData for attaching, something like this

    //Check if mail can be sent
    if ([MFMailComposeViewController canSendMail])
        {
            MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
            mailer.mailComposeDelegate = self;
    
           // Add NSData you got as screenshot to attachment
           [mailer addAttachmentData:theImageData mimeType:@"image/jpeg" fileName:[NSString stringWithFormat:@"test.jpg"]];  
            [self presentModalViewController:mailer animated:YES];
    
        }
    

    EDIT:

    3. Sending image through SMS

        // Will Work only for iOS 7
    
        MFMessageComposeViewController* messageComposer = [[MFMessageComposeViewController alloc] init];
         messageComposer.messageComposeDelegate = self; // As mentioned by the OP in comments, we have to set messageComposeDelegate to self.
         messageComposer.recipients = [NSArray arrayWithObject:@"123456789"];
    
     if([MFMessageComposeViewController canSendText])
      {
    
        if([MFMessageComposeViewController respondsToSelector:@selector(canSendAttachments)] && [MFMessageComposeViewController canSendAttachments])
        {
            NSString* uti = (NSString*)kUTTypeMessage;
            [messageComposer addAttachmentData:theImageData typeIdentifier:uti filename:@"filename.jpg"];
        }
    
        [self presentViewController:messageComposer animated:YES completion:nil];
      }
    

    Handle the delegate callbacks from MFMessageComposeViewController

    - (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
    {
    
    }