PDF Saved to Documents Directory never gets Attached (data is nil) the first time a MFMailCompose is Run, but is there every other time

StackOverflow https://stackoverflow.com/questions/22915618

문제

I have what seems to be a very common problem and so far, no Stack Overflow answer has helped out with this.

I have a simple function to email out a PDF attached to an email in my app, using MFMailComposeViewController. The PDF is populated with data from Event Core Data. So the user fills in some information and the UITableView consists of the unique events. The user selects an event and the email button appears in the NavigationBar, allowing them to send out an email for that event with the Event information appended to the PDF.

Here's my code:

- (IBAction)savePDFAndEmail:(id)sender
{
    pageSize = CGSizeMake(612, 792);
    NSString *string = self.occasion.title;    
    NSString *fileName = [NSString stringWithFormat:@"%@.pdf", resultString];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];

    // NSMutableData *data = [NSMutableData dataWithContentsOfFile:pdfFileName];
    NSData *data=[NSData dataWithContentsOfFile:pdfFileName];
    [self createPDF:pdfFileName];

    NSLog(@"Data is %@", data);

    if ([MFMailComposeViewController canSendMail])
    {
        MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];

        mailer.mailComposeDelegate = self;
        [mailer setSubject:@"An email"];
        [mailer addAttachmentData:data mimeType:@"application/pdf" fileName:fileName];

        NSString *emailBody = @"Please find attached PDF";
        [mailer setMessageBody:emailBody isHTML:NO];

        [self presentViewController:mailer animated:YES completion:^{
            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

        }];
    }

}

UPDATE: The createPDF method is:

- (void)createPDF:(NSString *)fileName
{
    CGContextRef pdfContext;
    CFStringRef path;
    CFURLRef url;
    CGSize textSize = CGSizeMake(pageSize.width - 5*kBorderInset-5*kMarginInset, pageSize.height - 5*kBorderInset - 5*kMarginInset);
    CGRect pageRect = CGRectMake(kBorderInset + kMarginInset, kBorderInset + kMarginInset + 50.0, pageSize.width - 2*kBorderInset - 2*kMarginInset, textSize.height);
    CFMutableDictionaryRef myDictionary = NULL;
    const char *filename = [fileName UTF8String];

    // Create a CFString from the filename we provide to this method when we call it
    path = CFStringCreateWithCString (NULL, filename,
                                      kCFStringEncodingUTF8);
    // Create a CFURL using the CFString we just defined
    url = CFURLCreateWithFileSystemPath (NULL, path,
                                         kCFURLPOSIXPathStyle, 0);
    //CFRelease (path);
    // This dictionary contains extra options mostly for 'signing' the PDF
    myDictionary = CFDictionaryCreateMutable(NULL, 0,
                                             &kCFTypeDictionaryKeyCallBacks,
                                             &kCFTypeDictionaryValueCallBacks);
    CFDictionarySetValue(myDictionary, kCGPDFContextTitle, (__bridge_retained CFStringRef)fileName);
    CFDictionarySetValue(myDictionary, kCGPDFContextCreator, (__bridge_retained CFStringRef)fileName);

    // Create our PDF Context with the CFURL, the CGRect we provide, and the above defined dictionary
    pdfContext = CGPDFContextCreateWithURL (url, &pageRect, myDictionary);
...

It's getting it's information from Core Data to populate the PDF.

This is very standard code. I'm creating the PDF on the fly and attaching it to this email and just like every other related issue on Stack Overflow (there are hundreds), the PDF is "attached" to the email when I create it. But when I send out the email, there's no attached pdf. In my sent items of my Mail, there's the email but no attached PDF. If I go back to the app and send the same pdf again, that second email contains the PDF when I receive it.

The NSLog for the data shows everything.

When a new event is created, the NSLog is "Null". If I send the email on and go back to that same event, the data is now consisting of a series of numbers (not-null).

I put in some breakpoints and traced it and true enough, the data is null but the filePath doesn't also get appended the first time around.

You don't even have to send the email; you can simply activate the MFMailComposeViewController and delete the existing draft (by pressing cancel) and then open it again and now the Data is not null. That's obviously bad UI.

Problem

The problem is simply the fact that the PDF is never being attached to the email (data is null), the first time the user sends out a PDF for the selected event. It appears every other time.

Any thoughts on this would really be appreciated.

도움이 되었습니까?

해결책

Logically you should create pdf then read data and attach to mail. But in code I see different

Can you please switch those two lines and try:

[self createPDF:pdfFileName];
NSData *data=[NSData dataWithContentsOfFile:pdfFileName];

First create pdf then read it to NSData

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top