Crash On MFMailComposeViewController For iPad - email

- (void) mailshareClick:(UIButton *)sender
{
NSString *_message = #"wait for set up Mail";
[self waitForWhile:_message];
if ([MFMailComposeViewController canSendMail]){
[NSThread detachNewThreadSelector:#selector(mailFunction) toTarget:self withObject:nil];
}
else {
_message = #"Please set Mail account";
[self remove:_message];
}
}
- (void) mailFunction
{
NSData *data = nil;
if ([self.files.imageArr count]>0)
{
XXImage *single = [self.files.imageArr objectAtIndex:0];
UIImage *image = [[SDImageCache sharedImageCache] imageFromKey:[[single.imagearray objectAtIndex:0] columnImage]];
data = [UIImageJPEGRepresentation(image, 1.0f) retain];
}
[self performSelectorOnMainThread:#selector(mailFinished:) withObject:data waitUntilDone:YES];
[data release];
}
- (void) mailFinished:(NSData *)_data
{
if ([MFMailComposeViewController canSendMail]){
NSData *data = [_data retain];
MFMailComposeViewController *message = [[MFMailComposeViewController alloc] init];
//Title
[message setSubject:self.files.title];
//Body
[message setMessageBody:#"111" isHTML:YES];
[message setToRecipients:[NSArray arrayWithObject:#"mail"]];
//Content
if (data != nil) {
NSString *picStr = [[NSString alloc] initWithFormat:#"%#%#",OutsideWebsite_Normal,self.files.middlePicPath];
[message addAttachmentData: data mimeType: #"" fileName:picStr];
[picStr release];
[data release];
}
message.mailComposeDelegate = self;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
message.modalPresentationStyle = UIModalPresentationFormSheet;
}
[self presentModalViewController:message animated:YES];
[self remove:#"Set up Ok"];
[message release];
}
}
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
switch (result) {
case MFMailComposeResultSent:
{
NSLog(#"MFMailComposeResultSent");
break;
}
case MFMailComposeResultSaved:
{
NSLog(#"MFMailComposeResultSaved");
break;
}
case MFMailComposeResultFailed:
{
NSLog(#"MFMailComposeResultFailed");
break;
}
case MFMailComposeResultCancelled:
{
NSLog(#"MFMailComposeResultCancelled");
break;
}
default:
break;
}
[self performSelector:#selector(delayDismissModalView) withObject:nil afterDelay:1];
}
-(void)delayDismissModalView
{
[self dismissModalViewControllerAnimated:YES];
}
After invoke a few times the email method , there will be
[MFSearchResultsViewController hash]: message sent to deallocated instance
Or
[MFMailComposeViewController hash]: message sent to deallocated instance
crash.
As you think of that, what is the MFSearchResultsViewController function.
Whether it can solve the problem,please give me a hand.

You have to setDelegate for the mail controller. If you set the delegate to "self", make sure that the "self" has <MFMailComposeViewControllerDelegate>. If all these can't make it work, make sure you didn't call presentModalViewController twice.

Related

Get file name and Data Type from ELCAlbumPickerController

I am working on ELCAlbumPickerController, i am able to select multiple images and upload, but in addition i want to get the file name and datatype of the file. how can i do that?
I am able to select either image or video , how can i select both image and video and any file at a time?
Please find my code below for your reference.
- (void)viewDidLoad {
UIImage *anImage = [UIImage imageNamed:#"elc-ios-icon.png"];
NSArray *Items = [NSArray arrayWithObjects:
#"A text line",
anImage, nil];
UIActivityViewController *ActivityView =
[[UIActivityViewController alloc]
initWithActivityItems:Items applicationActivities:nil];
[self presentViewController:ActivityView animated:YES completion:nil];
}
- (IBAction)launchController
{
ELCAlbumPickerController *albumController = [[ELCAlbumPickerController alloc] initWithNibName: nil bundle: nil];
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:albumController];
[albumController setParent:elcPicker];
[elcPicker setDelegate:self];
ELCImagePickerDemoAppDelegate *app = (ELCImagePickerDemoAppDelegate *)[[UIApplication sharedApplication] delegate];
if ([app.viewController respondsToSelector:#selector(presentViewController:animated:completion:)]){
[app.viewController presentViewController:elcPicker animated:YES completion:nil];
} else {
[app.viewController presentModalViewController:elcPicker animated:YES];
}
[elcPicker release];
[albumController release];
}
- (IBAction)launchSpecialController
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
self.specialLibrary = library;
[library release];
NSMutableArray *groups = [NSMutableArray array];
[_specialLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group) {
[groups addObject:group];
} else {
// this is the end
[self displayPickerForGroup:[groups objectAtIndex:0]];
}
} failureBlock:^(NSError *error) {
self.chosenImages = nil;
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Error" message:[NSString stringWithFormat:#"Album Error: %# - %#", [error localizedDescription], [error localizedRecoverySuggestion]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
NSLog(#"A problem occured %#", [error description]);
// an error here means that the asset groups were inaccessable.`
// Maybe the user or system preferences refused access.
}];
}
- (void)displayPickerForGroup:(ALAssetsGroup *)group
{
ELCAssetTablePicker *tablePicker = [[ELCAssetTablePicker alloc] initWithNibName: nil bundle: nil];
tablePicker.singleSelection = YES;
tablePicker.immediateReturn = YES;
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:tablePicker];
elcPicker.delegate = self;
tablePicker.parent = elcPicker;
// Move me
tablePicker.assetGroup = group;
[tablePicker.assetGroup setAssetsFilter:[ALAssetsFilter allAssets]];
if ([self respondsToSelector:#selector(presentViewController:animated:completion:)]){
[self presentViewController:elcPicker animated:YES completion:nil];
} else {
[self presentModalViewController:elcPicker animated:YES];
}
[tablePicker release];
[elcPicker release];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
return YES;
} else {
return toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
}
}
#pragma mark ELCImagePickerControllerDelegate Methods
- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
if ([self respondsToSelector:#selector(dismissViewControllerAnimated:completion:)]){
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[self dismissModalViewControllerAnimated:YES];
}
for (UIView *v in [_scrollView subviews]) {
[v removeFromSuperview];
}
CGRect workingFrame = _scrollView.frame;
workingFrame.origin.x = 0;
images = [NSMutableArray arrayWithCapacity:[info count]];
for(NSDictionary *dict in info) {
UIImage *image = [dict objectForKey:UIImagePickerControllerOriginalImage];
[images addObject:image];
UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
[imageview setContentMode:UIViewContentModeScaleAspectFit];
imageview.frame = workingFrame;
[_scrollView addSubview:imageview];
[imageview release];
workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
}
self.chosenImages = images;
NSLog(#"Images:%#",images);
[_scrollView setPagingEnabled:YES];
[_scrollView setContentSize:CGSizeMake(workingFrame.origin.x, workingFrame.size.height)];
for (int i=0; i< images.count; i++) {
NSData *image = UIImageJPEGRepresentation(images[i], 0.1);
NSLog(#"NSDATA:%#",image);
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:#"name=thefile&&filename=recording"];
[urlString appendFormat:#"%#", image];
NSLog(#"urlstring:%#",urlString);
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString * namecount=[NSString stringWithFormat:#"fn%i.png",i];
NSString * baseurl =[[NSString alloc]initWithFormat:#"http://199.198.12.555/serviceService.svc/serviceupload?fileName=%#",namecount];
NSURL *url = [NSURL URLWithString:baseurl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod: #"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:image];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[connection start];
}
NSLog(#"%#",images[0]);
NSLog(#"%lu",(unsigned long)images.count);
}
-(IBAction)upload:(id)sender{
}
- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
if ([self respondsToSelector:#selector(dismissViewControllerAnimated:completion:)]){
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[self dismissModalViewControllerAnimated:YES];
}
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload
{
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[_specialLibrary release];
[_scrollView release];
[super dealloc];
}
#end
#implementation APActivityProvider
- (id) activityViewController:(UIActivityViewController *)activityViewController
itemForActivityType:(NSString *)activityType
{
if ( [activityType isEqualToString:UIActivityTypePostToTwitter] )
return #"This is a #twitter post!";
if ( [activityType isEqualToString:UIActivityTypePostToFacebook] )
return #"This is a facebook post!";
if ( [activityType isEqualToString:UIActivityTypeMessage] )
return #"SMS message text";
if ( [activityType isEqualToString:UIActivityTypeMail] )
return #"Email text here!";
if ( [activityType isEqualToString:#"it.albertopasca.myApp"] )
return #"OpenMyapp custom text";
return nil;
}
- (id) activityViewControllerPlaceholderItem:(UIActivityViewController *)activityViewController { return #""; }
#end
#implementation APActivityIcon
- (NSString *)activityType { return #"it.albertopasca.myApp"; }
- (NSString *)activityTitle { return #"Open Maps"; }
- (UIImage *) activityImage { return [UIImage imageNamed:#"elc-ios-icon.png"]; }
- (BOOL) canPerformWithActivityItems:(NSArray *)activityItems { return YES; }
- (void) prepareWithActivityItems:(NSArray *)activityItems { }
- (UIViewController *) activityViewController { return nil; }
- (void) performActivity {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"maps://"]];
}
#end
Thanks
You can get the asset URL using the key UIImagePickerControllerReferenceURL which would give the 'name', but that probably won't be very useful as its probably a UUID. The UIImagePickerControllerMediaType key contains the type.

Show waiting view when sending mail using smtp connection ios?

I am working on a app in which I am sending mail using mail-core engine. I have created my own viewController to send mail. I want to show a waiting view when mail sending is in process. My waiting view always displays after mail sending has been done. Is it some kind of threading issue?
Here is the code which I'm using to send mail.
- (IBAction) sendTapped:(id) sender {
[txtfSubject resignFirstResponder];
[txtfReceptient resignFirstResponder];
[txtvMessageBody resignFirstResponder];
[self setTo:txtfReceptient.text];
[self setFrom:username];
[self setSubject:txtfSubject.text];
[self setBody:txtvMessageBody.text];
[self performSelector:#selector(prepareAndSendMail) withObject:nil afterDelay:0.34];
}
- (void) prepareAndSendMail {
[WNAppDelegate performSelectorOnMainThread:#selector(showWaitingView) withObject:nil waitUntilDone:NO];
//TODO: send mail here
CTCoreMessage *msg = [[CTCoreMessage alloc] init];
[msg setTo:[myMessage to]];
[msg setFrom:[myMessage from]];
//Encode message here
NSString *encodedMessage = nil;
#try {
encodedMessage = [self encodeMessage:txtvMessageBody.text];
}
#catch (NSException * e) {
NSLog(#"An exception occurred while encoding message");
}
#finally {
if(encodedMessage){
[msg setBody:encodedMessage];
}
}
[msg setSubject:[myMessage subject]];
BOOL success = [self sendMailOnAnotherThread:msg];
[msg release];
[WNAppDelegate performSelectorOnMainThread:#selector(removeWaitingView) withObject:nil waitUntilDone:NO];
//[appDelegate removeWaitingView];
if(!success) {
UIAlertView * empty_alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Could not send."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[empty_alert show];
[empty_alert autorelease];
return;
}
else {
//Message sent successfully
if(self.target && [self.target respondsToSelector:#selector(messageSentSuccessfully)]){
[self.target messageSentSuccessfully];
}
WN_POST_NOTIFICATION(kMessageSentSuccessfully,nil);
}
[self dismissModalViewControllerAnimated:YES];
}
- (BOOL) sendMailOnAnotherThread:(CTCoreMessage*)message {
BOOL success = YES;
BOOL auth = YES;
BOOL tls = YES;
#try {
[CTSMTPConnection sendMessage:message server:GMAIL_SERVER username:username
password:password port:GMAIL_PORT_Number useTLS:tls useAuth:auth];
}
#catch (NSException * e) {
//Msg failed to send;
success = FALSE;
}
return success;
}
Ok guys,Thanks for all the info you have provided. The problem is now solved.
I'M posting here my code in case some one need it.
- (IBAction) sendTapped:(id) sender {
[txtfSubject resignFirstResponder];
[txtfReceptient resignFirstResponder];
[txtvMessageBody resignFirstResponder];
[self setTo:txtfReceptient.text];
[self setFrom:username];
[self setSubject:txtfSubject.text];
[self setBody:txtvMessageBody.text];
[self performSelector:#selector(prepareAndSendMail) withObject:nil afterDelay:0.34];
}
- (void) prepareAndSendMail {
//[((WalnutAppDelegate*)WNAppDelegate) performSelectorOnMainThread:#selector(showWaitingView) withObject:nil waitUntilDone:NO];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSThread *aNewThread = [[[NSThread alloc] initWithTarget:((WalnutAppDelegate*)WNAppDelegate) selector:#selector(showWaitingView) object:nil] autorelease];
[aNewThread start];
//[NSThread detachNewThreadSelector: toTarget:((WalnutAppDelegate*)WNAppDelegate) withObject:nil];
//TODO: send mail here
CTCoreMessage *msg = [[CTCoreMessage alloc] init];
[msg setTo:[myMessage to]];
[msg setFrom:[myMessage from]];
//Encode message here
NSString *encodedMessage = nil;
#try {
encodedMessage = [self encodeMessage:txtvMessageBody.text];
}
#catch (NSException * e) {
NSLog(#"An exception occurred while encoding message");
}
#finally {
if(encodedMessage){
[msg setBody:encodedMessage];
}
}
[msg setSubject:[myMessage subject]];
BOOL success = [self sendMailOnAnotherThread:msg];
[msg release];
//[NSThread detachNewThreadSelector:#selector(removeWaitingView) toTarget:((WalnutAppDelegate*)WNAppDelegate) withObject:nil];
[((WalnutAppDelegate*)WNAppDelegate) performSelectorOnMainThread:#selector(removeWaitingView) withObject:nil waitUntilDone:NO];
[pool drain];
if(!success) {
UIAlertView * empty_alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Could not send."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[empty_alert show];
[empty_alert autorelease];
return;
}
else {
//Message sent successfully
if(self.target && [self.target respondsToSelector:#selector(messageSentSuccessfully)]){
[self.target messageSentSuccessfully];
}
WN_POST_NOTIFICATION(kMessageSentSuccessfully,nil);
}
[self dismissModalViewControllerAnimated:YES];
}
- (BOOL) sendMailOnAnotherThread:(CTCoreMessage*)message {
BOOL success = YES;
BOOL auth = YES;
BOOL tls = YES;
#try {
[CTSMTPConnection sendMessage:message server:GMAIL_SERVER username:username
password:password port:GMAIL_PORT_Number useTLS:tls useAuth:auth];
}
#catch (NSException * e) {
//Msg failed to send;
success = FALSE;
}
return success;
}
- (void)showWaitingView {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
CGRect frame = CGRectMake(90, 190, 32, 32);
UIActivityIndicatorView* progressInd = [[UIActivityIndicatorView alloc] initWithFrame:frame];
[progressInd startAnimating];
progressInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
frame = CGRectMake(130, 193, 140, 30);
UILabel *waitingLable = [[UILabel alloc] initWithFrame:frame];
waitingLable.text = #"Processing...";
waitingLable.textColor = [UIColor whiteColor];
waitingLable.font = [UIFont systemFontOfSize:20];;
waitingLable.backgroundColor = [UIColor clearColor];
frame = [[UIScreen mainScreen] applicationFrame];
UIView *theView = [[UIView alloc] initWithFrame:frame];
theView.backgroundColor = [UIColor blackColor];
theView.alpha = 0.7;
theView.tag = 999;
[theView addSubview:progressInd];
[theView addSubview:waitingLable];
[progressInd release];
[waitingLable release];
[window addSubview:[theView autorelease]];
[window bringSubviewToFront:theView];
[pool drain];
}
- (void)removeWaitingView {
UIView *v = [window viewWithTag:999];
if(v) [v removeFromSuperview];
}
Yes it is. You need to return to run loop in order to get UI updated. So it is best to display the waiting view in main thread, send mail in background thread and then again hide and remove waiting view in main thred. You should only update UI from main thread. You can use performSelectorInBackground and performSelectorOnMainThread to do it the easy way without creating threads manually. You can also use dispatch_async like this:
//show waiting view
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//prepare mail here
dispatch_async(dispatch_get_main_queue(), ^{
//send mail
//hide waiting view
});
});
Since you are executing prepareAndSendMail on the main thread, WNAppDelegate performSelectorOnMainThread:#selector(showWaitingView) withObject:nil waitUntilDone:NO]; will call showWaitingView after the current run loop has ended by which time you will have sent the mail. Setting waitUntilDone: to YES will show the waiting view at the time you intend it to.

MFMailComposeViewController loads a blank white screen

I'm testing on an iPod Touch running OS 3.1.3
Trying to allow users to send an email from within the app - but when the following code is executed, the entire screen just turns completely blank / white.
Any ideas on why this is happening?
I've got the MessageUI framework in the project.
I'm importing and delegating in the header file:
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>
<MFMailComposeViewControllerDelegate>
And here's the code, pretty standard:
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"App Feedback"];
[picker setToRecipients:[NSArray arrayWithObject:#"xyz#gmail.com"]];
[self presentModalViewController:picker animated:YES];
[picker release];
}
And then I have the didFinishWithResult function that would dismiss the ModalViewController when the email has been sent.
But again, all I get is a blank white screen on my iPod Touch. =/
Thanks!
if([MFMailComposeViewController canSendMail]){
MFMailComposeViewController *mail=[[MFMailComposeViewController alloc]init];
mail.mailComposeDelegate=self;
[mail setSubject:#"App Feedback"];
[mail setMessageBody:#"*your message content*" isHTML:NO];
[self presentModalViewController:mail animated:YES];
[mail release];
}
- (void)mailComposeController:(MFMailComposeViewController*)mailController didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[self dismissModalViewControllerAnimated:YES];
}
You can take look at sample code from apple:
http://developer.apple.com/library/ios/#samplecode/MessageComposer/Listings/Classes_MessageComposerViewController_m.html
-(IBAction)showMailPicker:(id)sender {
Class mailClass = (NSClassFromString(#"MFMailComposeViewController"));
if (mailClass != nil) {
[self displayMailComposerSheet];
if ([mailClass canSendMail]) {
[self displayMailComposerSheet];
}
else {
feedbackMsg.hidden = NO;
feedbackMsg.text = #"Device not configured to send mail.";
}
}
else {
feedbackMsg.hidden = NO;
feedbackMsg.text = #"Device not configured to send mail.";
}
}
-(void)displayMailComposerSheet
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Hello from California!"];
NSArray *toRecipients = [NSArray arrayWithObject:#"first#example.com"];
NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com", #"third#example.com", nil];
NSArray *bccRecipients = [NSArray arrayWithObject:#"fourth#example.com"];
[picker setToRecipients:toRecipients];
[picker setCcRecipients:ccRecipients];
[picker setBccRecipients:bccRecipients];
NSString *path = [[NSBundle mainBundle] pathForResource:#"rainy" ofType:#"jpg"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:#"image/jpeg" fileName:#"rainy"];
NSString *emailBody = #"It is raining in sunny California!";
[picker setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:picker animated:YES];
[picker release];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
feedbackMsg.hidden = NO;
// Notifies users about errors associated with the interface
switch (result)
{
case MFMailComposeResultCancelled:
feedbackMsg.text = #"Result: Mail sending canceled";
break;
case MFMailComposeResultSaved:
feedbackMsg.text = #"Result: Mail saved";
break;
case MFMailComposeResultSent:
feedbackMsg.text = #"Result: Mail sent";
break;
case MFMailComposeResultFailed:
feedbackMsg.text = #"Result: Mail sending failed";
break;
default:
feedbackMsg.text = #"Result: Mail not sent";
break;
}
[self dismissModalViewControllerAnimated:YES];
}

mail application are not launching!

i am trying to implement the functionality of email in my application. i have added MessageUI-framework, along with header and MFMailComposeViewControllerDelegate protocol but i am facing problem. here is my code:
- (void)viewDidLoad {
[super viewDidLoad];
if(isViewPushed == NO) {
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemCompose
target:self action:#selector(email)] autorelease];
}
}
-(void) email
{
NSMutableString *emailBody = [[[NSMutableString alloc] initWithString:#"<html><body>"] retain];
[emailBody appendString:#"<p>type text here</p>"];
UIImage *emailImage = [UIImage imageNamed:#"20-gear2.png"];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(emailImage)];
[emailBody appendString:[NSString stringWithFormat:#"<p><b><img src='data:image/png;base64.....,.......%#'></b></p>",imageData]];
[emailBody appendString:#"</body></html>"];
MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];
emailDialog.mailComposeDelegate = self;
[emailDialog setSubject:#"My Inline Image Document"];
[self presentModalViewController:emailDialog animated:YES];
[emailDialog release];
if(! [MFMailComposeViewController canSendMail])
{
UIAlertView *cantMailAlert = [[UIAlertView alloc]
initWithTitle:#"cant email"
message:#"nt able to send email"
delegate:NULL
cancelButtonTitle:#"ok"
otherButtonTitles:NULL];
[cantMailAlert show];
[cantMailAlert release];
return;
}
MFMailComposeViewController *mailController = [[[MFMailComposeViewController alloc] init] autorelease];
[mailController setMessageBody:#"can send my mail" isHTML:NO];
mailController.mailComposeDelegate = self;
[self presentModalViewController:mailController animated:YES];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
if (error)
{
UIAlertView *cantMailAlert = [[UIAlertView alloc]
initWithTitle:#"mail error"
message: [error localizedDescription]
delegate:NULL
cancelButtonTitle:#"ok"
otherButtonTitles:NULL];
[cantMailAlert show];
[cantMailAlert release];
return;
}
NSString *resultString;
switch (result)
{
case MFMailComposeResultSent:
resultString = #"sent mail";
break;
case MFMailComposeResultSaved:
resultString = #"saved";
break;
case MFMailComposeResultCancelled:
resultString = #"cancel";
break;
case MFMailComposeResultFailed:
resultString = #"failed";
break;
}
if (resultString = #"saved")
{
NSString *msg = [NSString stringWithFormat:#"%# at %#\n", resultString, [NSDate date]];
UIAlertView *MailAlert = [[UIAlertView alloc]
initWithTitle:#"status"
message: msg
delegate:NULL
cancelButtonTitle:#"ok"
otherButtonTitles:NULL];
[MailAlert show];
[MailAlert release];
return;
}
[controller dismissModalViewControllerAnimated:YES];
[controller release];
//[self email];
}
but when i click on mail button then applictaion terminates and starts loading . it says can't able to store privious value!!
Why are you presenting two instances of MFMailcomposeviewcontroller in viewDidLoad? Why are you creating two objects namely emailDialog and mailController and presenting them?

How to send mail from iphone app?

I am try to send mail from my app. I want to type(dynamically) recipient id,ccid,sub and message.
Thanks
Senthilkumar
on iOS 3+
Import #import in your view controller header.
Then:
-(void)showMailPanel {
MFMailComposeViewController *mailComposeViewController = [[MFMailComposeViewController alloc] init];
// only on iOS < 3
//if ([MFMailComposeViewController canSendMail] == NO)
// [self launchMailApp]; // you need to
mailComposeViewController.mailComposeDelegate = self;
[mailComposeViewController setToRecipients:[NSArray arrayWithObjects:#"email address1",#"email address 2",nil]];
[mailComposeViewController setSubject:#"your subject"];
[mailComposeViewController setMessageBody:#"your body" isHTML:YES];
mailComposeViewController.delegate = self;
[self.navigationController presentModalViewController:mailComposeViewController animated:YES];
[mailComposeViewController release];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
// Notifies users about errors associated with the interface
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(#"Result: canceled");
break;
case MFMailComposeResultSaved:
NSLog(#"Result: saved");
break;
case MFMailComposeResultSent:
NSLog(#"Result: sent");
break;
case MFMailComposeResultFailed:
NSLog(#"Result: failed");
break;
default:
NSLog(#"Result: not sent");
break;
}
[controller dismissModalViewControllerAnimated:YES];
}
-(void)launchMailApp {
{
NSString *recipients = #"dest_email";
NSString *email = [NSString stringWithFormat:#"%#%#", recipients, subject];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}
You need things like this:
//Import this in your .h file
#import <MessageUI/MessageUI.h>
...
MFMailComposeViewController *mailController = [[[MFMailComposeViewController alloc] init] autorelease];
mailController.mailComposeDelegate = self;
[mailController setSubject:[NSString stringWithFormat:#"Report a problem - #%#", yourUserID]];
[mailController setToRecipients:[NSArray arrayWithObject:#"support#yourWebsite.com"]];
[self presentModalViewController:mailController animated:YES];
Besides, the parent view controller (the delegate) needs to conform to the MFMailComposeViewControllerDelegate protocol:
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
//Extra implementation here...
[self dismissModalViewControllerAnimated:YES];
}