Search code examples
iosobjective-cemailemail-attachmentsmfmailcomposeviewcontroller

Attaching .mov to MFMailComposeViewController


I want to send .mov file via email. So I am using MFMailComposeViewController. After spending some time for searching I finally wrote below code.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:
                                     [NSString stringWithFormat:@"/Saved Video/%@",[player.contentURL lastPathComponent]]];
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.mailComposeDelegate = self;
[mail addAttachmentData:[NSData dataWithContentsOfURL:[NSURL URLWithString:myPathDocs]] mimeType:@"video/quicktime" fileName:[myPathDocs lastPathComponent]];
[mail setSubject:@"Share VIDEO by My App"];
[self presentViewController:mail animated:YES completion:nil]; 

When Mail composer appears I can see attachment in the mail body but I receive this mail without attachment.
Am I missing something? or Doing something wrong?

Please help me.


Solution

  • You aren't getting the data for the file correctly.

    The first step is to split up your code so it's more readable and far easier to debug. Split this line:

    [mail addAttachmentData:[NSData dataWithContentsOfURL:[NSURL URLWithString:myPathDocs]] mimeType:@"video/quicktime" fileName:[myPathDocs lastPathComponent]];
    

    into these:

    NSURL *fileURL = [NSURL URLWithString:myPathDocs];
    NSData *fileData = [NSData dataWithContentsOfURL:fileURL];
    [mail addAttachmentData:fileData mimeType:@"video/quicktime" fileName:[myPathDocs lastPathComponent]];
    

    Now when you debug this code you will find that fileData is nil. fileURL will also be nil (or at least an invalid URL).

    Change this line:

    NSURL *fileURL = [NSURL URLWithString:myPathDocs];
    

    to:

    NSURL *fileURL = [NSURL fileURLWithPath:myPathDocs];
    

    You need to do this since myPathDocs is a file path, not a URL string.

    Also, you should fix how you build myPathDocs. Instead of:

    NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:
                                 [NSString stringWithFormat:@"/Saved Video/%@",[player.contentURL lastPathComponent]]];
    

    You should do something like:

    NSString *myPathDocs = [[documentsDirectory stringByAppendingPathComponent:@"Saved Video"] stringByAppendingPathComponent:[player.contentURL lastPathComponent]];