Search code examples
iphonexcodemfmailcomposeviewcontroller

Save PDF then send in email


I am trying to save a pdf from a url and then send it in an email. The sender seems to have it but the receiver does not get it.

When I do a NSLog of the NSString file I get /var/mobile/Applications/0ADE222E-6346-4C6C-8348-DA5327B980AA/Documents/myPDF.pdf

It seems like it saves but it doesn't send. Here is my code below for saving and sending

EDIT

Updated code

    // This pdfURL is 0 bytes
    NSData *pdfURL = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",webPage.urlString]]];

    //Store the Data locally as PDF File
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    NSString *file = [documentDirectory stringByAppendingFormat:@"/myPDF.pdf"];

    [pdfURL writeToFile:file atomically:YES];

    //Sending the pdf
    MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init];
    composer.mailComposeDelegate = self;        
    if ([MFMailComposeViewController canSendMail]){
        //Changed email for privacy issues
        [composer setToRecipients:[NSArray arrayWithObjects:@"[email protected]", nil]];
        [composer setSubject:[NSString stringWithFormat:@"%@ email",titleText]];
        [composer setMessageBody:@"your custom body content" isHTML:NO];

        NSLog(@"pdf %@",file);
        // This pdfData is 0 bytes
        NSData *pdfData = [NSData dataWithContentsOfFile:file];

        [composer addAttachmentData:pdfData mimeType:@"application/pdf" fileName:@"myPDF.pdf"];

        [composer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
        [self presentModalViewController:composer animated:YES];            
    }

Solution

  • The issue was with the webPage.urlString being empty. This code works just make sure the url string is not empty :P