Objective-C (iOS): 写真付きメールを送る

MailViewController

MessageUI.framework をリンクしておきます。

Objective-C: MailViewController.h

#import <UIKit/UIKit.h>
#import <MessageUI/MFMailComposeViewController.h>

@interface MailViewController : UIViewController <MFMailComposeViewControllerDelegate>

@end

Objective-C: MailViewController.m

#import "MailViewController.h"

@interface MailViewController ()

@end

@implementation MailViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(50, 50, 150, 50);
    [button setTitle:@"写メを送る" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonWasTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)buttonWasTapped:(UIButton *)button {
    [self emailPhoto:[UIImage imageNamed:@"sample"]];
}

- (void)emailPhoto:(UIImage *)image
{
	MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
	[mailViewController setSubject:@"写真を添付しました"];
	[mailViewController addAttachmentData:[NSData dataWithData:UIImagePNGRepresentation(image)] mimeType:@"image/png" fileName:@"Photo.png"];
    [mailViewController setMessageBody:@"みてね" isHTML:NO];
	mailViewController.mailComposeDelegate = self;
	
    [self.navigationController presentViewController:mailViewController animated:YES completion:nil];
	
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error{
	
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
	
	NSString *mailError = nil;
	switch (result) {
		case MFMailComposeResultSent:
            break;
		case MFMailComposeResultFailed:
            mailError = @"メールの送信に失敗しました";
			break;
		default:
			break;
	}
	
	if (mailError != nil) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:mailError delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
	}
	
}


@end