I'm diving into iOS development and am playing getting familiar with the MFMailComposeViewController class for sending emails with attachments. The data I'm trying to attach is information collected at run time, stored in an NSDictionary, and serialized to NSData, but every time the email is sent, there's no sign of an attachment. My code first display the MFMailComposeViewController view with the recipient email, body, and subject lines already filled in. Then I display an alert box to ask the user if I can collect some anonymous data. If they click yes, my alert view callback method compiles the data and attaches it to the MFMailComposeViewController. All the data appears correct when I step through it in the debugger, but the attached data never arrives with the email. Here's my code...
-(void)displayComposerSheet
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:@"Temp Subject Line"];
NSArray *toRecipients = [NSArray arrayWithObjects:@"[email protected]", nil];
[picker setToRecipients:toRecipients];
NSString *emailBody = @"Temporary email body";
[picker setMessageBody:emailBody isHTML:NO];
[self setMailViewController:picker];
[self presentModalViewController:picker animated:YES];
UIAlertView* uiav= [[UIAlertView alloc] initWithTitle: @"May we collect data from you?"
message: @"May we collect some data form you?"
delegate: self cancelButtonTitle: @"No" otherButtonTitles: nil];
[uiav addButtonWithTitle:@"Yes"];
[uiav setDelegate:self];
[uiav show];
[uiav release];
[picker release];
}
- (void) alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 1)
{
NSMutableDictionary *appData = [[[NSMutableDictionary alloc] init] autorelease];
.
. //Compile the application data to attach to email
.
NSString *errorString = [[[NSString alloc] init] autorelease];
NSData *attachData = [NSPropertyListSerialization dataFromPropertyList:appData format:NSPropertyListXMLFormat_v1_0 errorDescription:&errorString];
[[self mailViewController] addAttachmentData:attachData mimeType:@"text/xml" fileName:@"app data"];
}
}
}
Any ideas? Does it have anything to do with the fact that I'm trying to attach the data AFTER I load the MFMailComposeViewController?
Thanks so much for your wisdom!
Your suspicion is correct.
Quoth the documentation
...after presenting the interface, your application is not allowed to make further changes to the email content. The user may still edit the content using the interface, but programmatic changes are ignored. Thus, you must set the values of content fields before presenting the interface.