可以在iOS程序中使用MFMailComposeViewController发送邮件,代码如下:
#import "ViewController.h"
@import MessageUI;
@interface ViewController () <MFMailComposeViewControllerDelegate>
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)sendEMail:(id)sender {
// 1.初始化编写邮件的控制器
MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
if (!mailViewController) {
// 在设备还没有添加邮件账户的时候mailViewController为空,下面的present view controller会导致程序崩溃,这里要作出判断
NSLog(@"设备还没有添加邮件账户");
}
mailViewController.mailComposeDelegate = self;
// 2.设置邮件主题
[mailViewController setSubject:@"测试邮件"];
// 3.设置邮件主体内容
[mailViewController setMessageBody:@"一张图片" isHTML:NO];
// 4.添加附件
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"Heaven Lake" ofType:@"jpg"];
NSData *attachmentData = [NSData dataWithContentsOfFile:imagePath];
[mailViewController addAttachmentData:attachmentData mimeType:@"image/jpeg" fileName:@"天堂之珠:仙本那"];
// 5.呼出发送视图
[self presentViewController:mailViewController animated:YES completion:nil];
}
@end
这段代码在模拟器中可以顺利运行:
来到真机中跑的话,崩溃了:
2014-02-15 21:23:59.893 NoCrash_Mail[844:60b] 设备还没有添加邮件账户
2014-02-15 21:23:59.898 NoCrash_Mail[844:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target <ViewController: 0x1556e1b0>.'
*** First throw call stack:
(0x2f849e83 0x39ba66c7 0x320b61eb 0xcf71 0x32002da3 0x32002d3f 0x32002d13 0x31fee743 0x3200275b 0x32002425 0x31ffd451 0x31fd2d79 0x31fd1569 0x2f814f1f 0x2f8143e7 0x2f812bd7 0x2f77d471 0x2f77d253 0x344b72eb 0x32032845 0xd1dd 0x3a09fab7)
libc++abi.dylib: terminating with uncaught exception of type NSException
暴力调试法:
// 5.呼出发送视图
NSLog(@"5.");
[self presentViewController:mailViewController animated:YES completion:nil];
NSLog(@"崩溃了");
控制台输出如下:
2014-02-15 21:26:48.002 NoCrash_Mail[865:60b] 设备还没有添加邮件账户
2014-02-15 21:26:48.006 NoCrash_Mail[865:60b] 5.
2014-02-15 21:26:48.008 NoCrash_Mail[865:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target <ViewController: 0x17682d60>.'
可以看到在presentViewController方法调用后就崩溃了,另外用断点调试可以看到:
mailViewController一直都是nil的,所以在present一个nil控制器时程序崩溃了。
因此,我们要做好防御工作,如果mailViewController为nil就立即return从而终止下面语句的执行,并作出错处理:
// 1.初始化编写邮件的控制器
MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
if (!mailViewController) {
// 在设备还没有添加邮件账户的时候mailViewController为空,下面的present view controller会导致程序崩溃,这里要作出判断
NSLog(@"设备还没有添加邮件账户");
return;
}
程序没有崩溃,并且系统自动弹出警告框,mailViewController之所以为nil,是因为我的手机还没有设置邮件账户。
首先打开蜂窝或Wifi,然后打开Settings —— Mail, Contacts, Calendars —— Add Account,添加邮件账户,完成。
再运行,没问题了:
我们无法预测设备是否设置了邮件账户,所以做好防御工作很重要。