How to send an email with cocos2d

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

We will use MFMailComposeViewController, and we want to send a email with preformated subject and body, and an image as attachment:

email

First, add the MFMailComposeViewControllerDelegate to your .h, this delegate method will be called when you have finish using the controller (after cancelling or sending the email):

-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error

Here is the code, basically we pause the cocos2d animation, prepare the controller with the subject/body and a screenshot file which is previously saved to the document directory (see the previous blog post on how to take a screenshot for more details).

-(void)sendEmail 
{
    AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];

    [[CCDirector sharedDirector] pause];
    [[CCDirector sharedDirector] stopAnimation];

    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];

    if (!picker) //happens if no email is configured on your device
    {
        [[CCDirector sharedDirector] resume];
        [[CCDirector sharedDirector] startAnimation];
        return;
    }

    picker.mailComposeDelegate = self;
    [picker setSubject:@"This is test subject"];
    [picker setMessageBody:@"This is test message body" isHTML:YES];

    //take screenshot
    NSString *file = @"screenShot.png";
    [CCDirector sharedDirector].nextDeltaTimeZero = YES;
    CGSize windowSize = [CCDirector sharedDirector].winSize;
    CCRenderTexture *renderTexture = [CCRenderTexture renderTextureWithWidth:windowSize.width height:windowSize.height];
    [renderTexture begin];
    [self visit];
    [renderTexture end];
    [renderTexture saveToFile:file format:kCCImageFormatPNG];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *screenShotPath = [documentsDirectory stringByAppendingPathComponent:file];
    NSData *data = [NSData dataWithContentsOfFile:screenShotPath];
    UIImage *image = [UIImage imageWithData:data];
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    [picker addAttachmentData:data mimeType:@"image/png" fileName:@"attachment.png"];

    [[app navController] presentModalViewController:picker animated:YES];
}

-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    [[CCDirector sharedDirector] resume];
    [[CCDirector sharedDirector] startAnimation];
    [controller dismissModalViewControllerAnimated:NO];
}

3 Comments

  1. Steve says:

    I have spent literally HOURS trying to figure this out from dozens of websites all across raywenderlich and stack overflow. This example worked easily and immediately

    All I had to do:
    Paste the “-(void)mailComposeController:(” bit in my HelloWorld.h file right above the @end
    Paste the rest into HelloWorld.m
    Call the function [self sendEmail];

    BOOM, beautiful.

    I’m using a standard Cocos2d project, no view controllers, and the default “@interface HelloWorldLayer : CCLayer ” from a brand new project.

    One thing though: I previously added MessageUI.framework from project>Targets>Summary>Linked Frameworks and Libraries. I didn’t see this mentioned in your setup guide.

    If anyone is getting a “Parse Issue; Expected a Type” error off the “MFMailComposeViewController” line in the .h file, include the framework from “MessageUI.framework” in your Target>Summary>Linked Frameworks by hitting the plus button and stick a “#import ” at the top of your .h file

  2. Steve says:

    Sorry it didn’t like my tags; The framework is added with #include [MessageUI/MessageUI.h], except replace the [] with the GreaterThan LessThan symbols as in an HTML tag

    • lezard says:

      thanks Steven, indeed you need the messageui.framework … :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>