iosemaildocumentsmfmailcomposercaf

Attaching a recorded .caf file locatted in documents directory to mail iOS Xcode


I have files recorded by the user in the documents directory... displayed in a uitableview...

I placed this code in my didSelectRowAtIndexPath... Why doesn't this work?

     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",[directoryContents objectAtIndex:indexPath.row]]];
NSURL *audioURL = [NSURL URLWithString:fileName];
NSData *audioData = [NSData dataWithContentsOfURL:audioURL];

MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];

    mailer.mailComposeDelegate = self;

[mailer addAttachmentData:audioData mimeType:@"audio/caf" fileName:fileName];

Solution

  • You are creating the URL incorrectly. You need to use fileURLWithPath, not URLWithString.

    Also, this:

    NSString *fileName = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",[directoryContents objectAtIndex:indexPath.row]]];
    

    Should be:

    NSString *fileName = [documentsDirectory stringByAppendingPathComponent:[directoryContents objectAtIndex:indexPath.row]];
    

    There is no need for the string format.

    Last thing. Th file name passed to the addAttachment method should be just a file name, not a full pathname.