I am trying to attach a docx file when sending email but I am having trouble. These 2 lines are always nil. The variables filename and extension are not nil but file comes up as nil. Not sure if this matters but the docx file is dynamically generated, what if I were to use the NSData from the generated file instead of creating a new NSData variable here?
filepath = /Users/myself/components/file.docx
NSString *file = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
NSData *fileData
= [NSData dataWithContentsOfFile:file];
here is the code
-(void)sendEmail:(NSString*)filePath{
if ([MFMailComposeViewController canSendMail])
{
mailComposer = [[MFMailComposeViewController alloc]init];
mailComposer.mailComposeDelegate = self;
[mailComposer setToRecipients:@[@"name@gmail.com"]];
[mailComposer setSubject:@"Mobile File Attachment"];
[mailComposer setMessageBody:@"DocX file attached" isHTML:NO];
// Determine the file name and extension
if(![filePath isEqual:nil])
{
NSArray *filepart = [filePath componentsSeparatedByString:@"."];
NSString *filename = [filepart objectAtIndex:0];
NSString *extension = [filepart objectAtIndex:1];
// Get the resource path and read the file using NSData
NSString *file = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
NSData *fileData = [NSData dataWithContentsOfFile:file];
// Determine the MIME type
NSString *mimeType;
if ([extension isEqualToString:@"jpg"]) {
mimeType = @"image/jpeg";
} else if ([extension isEqualToString:@"png"]) {
mimeType = @"image/png";
} else if ([extension isEqualToString:@"doc"]) {
mimeType = @"application/msword";
} else if ([extension isEqualToString:@"docx"]) {
mimeType = @"application/msword";
} else if ([extension isEqualToString:@"ppt"]) {
mimeType = @"application/vnd.ms-powerpoint";
} else if ([extension isEqualToString:@"html"]) {
mimeType = @"text/html";
} else if ([extension isEqualToString:@"pdf"]) {
mimeType = @"application/pdf";
}
// Add attachment
[mailComposer addAttachmentData:fileData mimeType:mimeType fileName:filename];
}
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:mailComposer animated:YES completion:nil];
}
EDIT: add value of filePath and this is how I generate the file
NSAttributedString *str = [[NSAttributedString alloc] initWithAttributedString:_textV.attributedText];
//convert to html then write to a .docx file to export to docx
NSData *data = [str dataFromRange:(NSRange){0, [str length]} documentAttributes:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} error:NULL];
[data writeToFile:@"/Users/myself/components/file.docx" atomically:YES];