iOS实现发送电子邮件的方法很简单,首先导入MessageUI.framework框架,然后代码如下:
1 #import "RPViewController.h" 2 3 //添加邮件头文件 4 #import5 6 @interface RPViewController () 7 8 @end 9 10 @implementation RPViewController11 12 - (void)viewDidLoad13 {14 [super viewDidLoad];15 // Do any additional setup after loading the view, typically from a nib.16 }17 18 - (void)didReceiveMemoryWarning19 {20 [super didReceiveMemoryWarning];21 // Dispose of any resources that can be recreated.22 }23 24 - (IBAction)click:(id)sender {25 if ([MFMailComposeViewController canSendMail]) {26 MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];27 picker.mailComposeDelegate = self;28 29 //在这里可以设定邮件的默认标题/内容,也可以设置收件人等30 [picker setSubject:@"标题"];31 NSString *emailBody = @"邮件内容";32 33 [picker setMessageBody:emailBody isHTML:NO];34 [self presentViewController:picker animated:YES completion:nil];35 // [picker release];36 }37 else {38 //无法发送邮件,在这里给用户提示39 }40 }41 42 #pragma mark 邮件代理方法43 - (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {44 switch (result) {45 case MFMailComposeResultCancelled:46 //取消发送47 break;48 case MFMailComposeResultSaved:49 //保存草稿50 break;51 case MFMailComposeResultSent:52 //发送成功53 break;54 case MFMailComposeResultFailed:55 //发送失败56 break;57 default:58 break;59 }60 61 [self dismissViewControllerAnimated:YES completion:nil];62 }63 64 @end
首先导入邮件的头文件,之后创建一个发送邮件用的控制器,设置默认参数,然后弹出这个控制器。
令当前控制器充当邮件控制器的代理,这样一来在邮件相关事件执行之后,就能给出一些用户提示了,也要在这里收起邮件视图。
发短信的道理完全一样,只是控制器换成了MFMessageComposeViewController,代理换成了MFMessageComposeViewControllerDelegate,配置代码如下:
1 if ([MFMessageComposeViewController canSendText]) {2 MFMessageComposeViewController *message = [[MFMessageComposeViewController alloc] init];3 message.messageComposeDelegate = self;4 5 message.recipients = @[@"电话号码"];6 message.body = @"内容";7 8 [self presentViewController:message animated:YES completion:nil];9 }