如何从iphone应用程序的文档目录中发送电子邮件文件

时间:2013-05-18 06:57:29

标签: iphone ipad email pdf nsdocumentdirectory

我正在保存文件文件目录之后,我想在电子邮件中发送该文件,但问题是它没有得到附加我认为问题是由于路径冲突或其他任何其他地方是我保存文件的代码。

//从iOS设备中检索文档目录

     NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
     NSString* documentDirectory = [documentDirectories objectAtIndex:0];
     NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];

//指示可变数据对象将其上下文写入磁盘上的文件

    [pdfData writeToFile:documentDirectoryFilename atomically:YES];
    NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);

以下是我用于在电子邮件中发送此文件的代码

    - (NSString *)pathForFile : (NSString *) fileName{

    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: fileName];
    }

  - (void) sendMailWithAttachedFile : (NSString *) fileName :(NSString *) extension{


MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
//    NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:[self pathForResourse:fileName ofType:extension]];
NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:[self pathForFile:[NSString stringWithFormat:@"%@.%@", fileName, extension]]];
NSData *data=[[NSData alloc]initWithContentsOfURL:outputURL];
[picker addAttachmentData:data mimeType:@"documents/pdf" fileName:@"TestOne.pdf"];
[self presentModalViewController:picker animated:YES];
}


  -(IBAction)onEmailResultPDF{


[self sendMailWithAttachedFile:@"TestOne":@"pdf"];

}

1 个答案:

答案 0 :(得分:1)

MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;

NSString *fileName = [[NSString alloc]initWithFormat:@"%@.pdf",giveFileName];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];

NSMutableData *myPdfData = [NSMutableData dataWithContentsOfFile:pdfFileName];
[picker addAttachmentData:myPdfData mimeType:@"application/pdf" fileName:giveFileName];
[self.navigationController presentViewController:picker animated:YES completion:nil];