iOS APP内部调用系统的邮件发送和分享文件
2017-09-10 本文已影响368人
yehkong
序言:app内部调用系统邮件发送和分享文件,其中文件作为邮件附件发送的email目标地址,使用了MessageUI Framework。
- 查看MessageUI框架,包含<MessageUI/MFMailComposeViewController.h>
<MessageUI/MFMessageComposeViewController.h>,前者是邮件发送,后者是短信发送,设计架构都是一致的。今天我主要整理邮件发送和分享文件。 - 使用的简要步骤暂且如下表述:
1.判断系统是否配置邮箱账户等;
2.MFMailComposeViewController实例并设置代理(需要注意是:代理属性是mailComposeDelegate,不是delegate,如果不小心写成了delegate就是UINavigationControllerDelegate的代理,而不是我们要的MFMailComposeViewControllerDelegate),并实现代理方法,处理取消发送、发送成功及发送失败等情况。
3.设置邮件主题、收件人、抄送和密送人等,这些也可以在稍后弹出来的系统UI由用户自行输入或添加。
4.通过addAttachmentData设置邮件的附件数据,也就是我们要发送和分享的文件。
5.将以上定制的MFMailComposeViewController实例实例present出来。 - 以下是具体实现的代码
##pragma mark - 邮件分享方法
#- (void)shareByEmail{
MFMailComposeViewController *mailSender = [[MFMailComposeViewController alloc]init];
mailSender.mailComposeDelegate = self;
[mailSender setSubject:NKLocalizedString(@"EmailFromMyApp")];
//以下为具体业务代码
data = [NSData dataWithContentsOfFile:path];//文件数据
NSString *extension;//文件类型识别字符串,如文件扩展名
NSString *mimeType = nil;//这个不能错,错了的话会闪退
if ([extension isEqualToString:@"MOV"] || [extension isEqualToString:@"MP4"]) {
mimeType = @"video/quicktime";
}else if ([extension isEqualToString:@"MP3"] || [extension isEqualToString:@"M4A"]) {
mimeType = @"audio/mpeg3";
}else if ([extension isEqualToString:@"JPG"] || [extension isEqualToString:@"JPEG"]) {
mimeType = @"image/jpeg";
}else if ([extension isEqualToString:@"PNG"]) {
mimeType = @"image/png";
}else if ([extension isEqualToString:@"TXT"]) {
mimeType = @"text/plain";
}else if ([extension isEqualToString:@"PDF"]) {
mimeType = @"application/pdf";
}else if ([extension isEqualToString:@"DOC"] || [extension isEqualToString:@"DOCX"]) {
mimeType = @"application/msword";
}else if ([extension isEqualToString:@"XLS"] || [extension isEqualToString:@"XLSX"]) {
mimeType = @"application/vnd.ms-exceld";
}else if ([extension isEqualToString:@"PPT"] || [extension isEqualToString:@"PPTX"]) {
mimeType = @"application/vnd.ms-powerpoint";
}else if ([extension isEqualToString:@"ZIP"]) {
mimeType = @"application/zip";
}else{
return ;
}
[mailSender addAttachmentData:data mimeType:mimeType fileName:name];
}
[self presentViewController:mailSender animated:YES completion:nil];
}
##pragma mark - MFMailComposeViewControllerDelegate
#- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
[controller dismissViewControllerAnimated:YES completion:nil];
switch (result) {
case MFMailComposeResultCancelled:
{
}
break;
case MFMailComposeResultSaved:
{
}
break;
case MFMailComposeResultSent:
{
showAlertMessage(nil, LocalizedString(@"HaveSent"));
}
break;
case MFMailComposeResultFailed:
{
}
break;
}
}