I have a bit of a strange problem. I am trying to send in-app email. So, I use MFMailComposeViewController for that.And I have realized MFMailComposeViewControllerDelegate.
When I click the send button, it should be dismissed immediately.In debug mode,it works well,BUT,in release mode,it is extremely slow so that user may click send button more than one time and the mail will be sent more than one time.
I have been confused for five days.
Anyone can help me ?
My code:
-(void)sendEMail
{
Class mailClass = (NSClassFromString(#"MFMailComposeViewController"));
if (mailClass != nil)
{
if ([mailClass canSendMail])
{
[self displayComposerSheet];
//[self launchMailAppOnDevice];
} else{
[self launchMailAppOnDevice];
}
} else {
[self launchMailAppOnDevice];
}
}
//可以发送邮件的话
-(void)displayComposerSheet
{
//mailPicker = [[MFMailComposeViewController alloc] init];
mailPicker.mailComposeDelegate = self;
//设置主题
[mailPicker setSubject: kEmailSubject];
// 添加发送者
NSArray *toRecipients = [NSArray arrayWithObject: kToRecipient];
//NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com", #"third#example.com", nil];
//NSArray *bccRecipients = [NSArray arrayWithObject:#"fourth#example.com", nil];
[mailPicker setToRecipients: toRecipients];
//[picker setCcRecipients:ccRecipients];
//[picker setBccRecipients:bccRecipients];
// 添加图片
// UIImage *addPic = [UIImage imageNamed: #"123.jpg"];
// NSData *imageData = UIImagePNGRepresentation(addPic); // png
// NSData *imageData = UIImageJPEGRepresentation(addPic, 1); // jpeg
// [mailPicker addAttachmentData: imageData mimeType: #"" fileName: #"123.jpg"];
NSString *emailBody = kEmailBody;
[mailPicker setMessageBody:emailBody isHTML:YES];
[self presentViewController:mailPicker animated:YES completion:nil];
}
-(void)sendMailBtnCLicked{
[mailPicker dismissViewControllerAnimated:YES completion:nil];
}
-(void)launchMailAppOnDevice
{
NSString *recipients = kToRecipient;
NSString *subject = kEmailSubject;
//#"mailto:first#example.com?cc=second#example.com,third#example.com&subject=my email!";
NSString *body = kEmailBody;
NSString *email = [NSString stringWithFormat:#"mailto:%#?subject=%#&body=%#", recipients, subject,body];
email = [email stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]];
}
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
if (result == MFMailComposeResultSent) {
[AccountManager sharedManager].isSentMail = YES;
}
[controller dismissViewControllerAnimated:YES completion:nil];
//[self dismissModalViewControllerAnimated:YES];
}
Stop other threads running background.
After the mail sent, restart them.
Related
I am new to iOS. I have a UITextfield and a Keyword Search Button. When ever I want to search a keyword from a service and press enter. Tt should display the related searched keyword from a service. Please help me to fix this issue? TIA!
- (IBAction)KeywordSearchClicked:(id)sender {
NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
[self KeywordcallSignupProfileService:dict];
}
-(void)KeywordcallSignupProfileService:(NSMutableDictionary *)dict
{
[SVProgressHUD showWithStatus:#"" maskType:SVProgressHUDMaskTypeBlack]; // Progress
NSString * post = [[NSString alloc]initWithFormat:#"userId=%#&key_word%#",UserId,[dict objectForKey:#"key_word"]];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.amarbiyashaadi.com/service/amarbiya-service.svc/userKeywordSearch/"]];
RBConnect = [[RBConnection alloc]init];
RBConnect.delegate = self;
[RBConnect postRequestForUrl:url postBody:post];
}
#pragma mark - MRConnection Delegate Methods
- (void)jsonData:(NSDictionary *)jsonDict
{
[SVProgressHUD dismiss];
NSMutableArray *jsonArr;
NSMutableDictionary *userDict,*dict;
NSArray *arr=[jsonDict allKeys];
jsonArr=[jsonDict objectForKey:#"DataTable"];
if (jsonArr.count>0) {
// Save credentials in user defaults
matchesProfileArr=[jsonArr mutableCopy];
DisplayTableViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:#"DisplayTableViewController"];
[self presentViewController:vc animated:YES completion:nil];
}
else
{
NSString *error=#"Somthing Went Wrong";
[SVProgressHUD showErrorWithStatus:error];
}
}
I have developed an app that allows the user to choose a video from the photo gallery and send it as an attachment in an email. I am able to choose a video from the gallery and proceed with sending the email but the video does not get attached with the email. There are no errors in the console.
ViewController.h:
#import <UIKit/UIKit.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <MessageUI/MessageUI.h>
#interface ViewController : UIViewController<UIImagePickerControllerDelegate, UINavigationControllerDelegate,MFMailComposeViewControllerDelegate>
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
- (IBAction)choose:(id)sender;
#end
ViewController.m:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIAlertController *myAlertController = [UIAlertController alertControllerWithTitle:#"MyTitle"
message: #"MyMessage"
preferredStyle:UIAlertControllerStyleAlert ];
[self presentViewController:myAlertController animated:YES completion:nil];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)choose:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
[self performSelector:#selector(email:) withObject:chosenImage afterDelay:0.5];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)email:(UIImage *)choosenImage{
NSString *iOSVersion = [[UIDevice currentDevice] systemVersion];
NSString *model = [[UIDevice currentDevice] model];
NSString *version = #"1.0";
NSString *build = #"100";
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
mailComposer.mailComposeDelegate = self;
[mailComposer setToRecipients:[NSArray arrayWithObjects: #"support#myappworks.com",nil]];
[mailComposer setSubject:[NSString stringWithFormat: #"MailMe V%# (build %#) Support",version,build]];
NSString *supportText = [NSString stringWithFormat:#"Device: %#\niOS Version:%#\n\n",model,iOSVersion];
supportText = [supportText stringByAppendingString: #"Please describe your problem or question."];
[mailComposer setMessageBody:supportText isHTML:NO];
NSData *data = UIImagePNGRepresentation(choosenImage);
[mailComposer addAttachmentData:data mimeType:#"image/png" fileName:#""];
[self presentViewController:mailComposer animated:YES completion:nil];
}
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Any suggestion/help would be much appreciated. Thank you.
You mentioned that you're trying to attach a video, and you've configured your UIImagePickerController to limit the mediaTypes to only videos. The problem then is that you're asking for the "edited image" in the "didFinishPickingMediaWithInfo" method:
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
The user did not pick an image - they picked a video. You need to use this instead:
NSURL *chosenVideoUrl = info[UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:chosenVideoUrl];
You can then pass the videoData to your email method and attach to the email. Be sure to update the mimeType from "image/png" to "video/mp4", as well.
If u need to attach both video and image you have write to code for both,but you written only for attaching an image.You can try the code below for getting both
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
if ([[info objectForKey:UIImagePickerControllerMediaType] isEqual:(NSString *)kUTTypeMovie]) {
NSString *videoURL = info[UIImagePickerControllerMediaURL];
[self emailImage:nil orVideo:videoURL];
}else {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
[self emailImage:chosenImage orVideo:nil];
}
[picker dismissViewControllerAnimated:YES completion:NULL];
}
UIImagePickerControllerMediaURL will return file url unlike UIImagePickerControllerEditedImage ,so can use NSData method dataWithContentsOfFile as bellow.
if (choosenImage) {
NSData *data = UIImagePNGRepresentation(choosenImage);
NSString *filename = [NSString stringWithFormat:#"Image_%#.png",TimeStamp];
[mailComposer addAttachmentData:data mimeType:#"image/png" fileName:filename];
[self presentViewController:mailComposer animated:YES completion:nil];
}else {
NSData *data = [NSData dataWithContentsOfFile:videoFile];
NSString *filename = [NSString stringWithFormat:#"Video_%#.mp4",TimeStamp];
[mailComposer addAttachmentData:data mimeType:#"video/mp4" fileName:filename];
[self presentViewController:mailComposer animated:YES completion:nil];
}
it will be good if you give a filename for the attachment it will be help full after it downloading.if you wish you can use a TimeStamp for that.
#define TimeStamp [NSString stringWithFormat:#"%f",[[NSDate date] timeIntervalSince1970] * 1000]
The email popup is not working in iOS 8 (Xcode 6). This popup is working fine in iOS 7 (Xcode 5). This pop up never works on simulator and on the device sometimes it works and sometimes it doesn't. Also I have seen the case that when i debug and execute each lines on debugging mode, it works but not so when I directly execute. Here's the code for MFMailComposerViewController inside the emailButtonPressed() method. Please suggest how can i solve this issue.
- (IBAction)emailButtonPressed:(id)sender {
if([MFMailComposeViewController canSendMail] == NO)
{
//Mail not configured correctly
CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(#"Email", #"HDR") message:NSLocalizedString(#"Email is not Configured", #"INF") delegate:nil cancelButtonTitle:NSLocalizedString(#"Ok", #"BTN") otherButtonTitles: nil];
[alert show];
return;
}
[[NSNotificationCenter defaultCenter] postNotificationName:kShowBusyIndicatoryEventName object:self];
MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
mailPicker.mailComposeDelegate = self;
[mailPicker setSubject:#""];
// Set up recipients
NSString *emailBody = #" ";
NSString *fileName = #" ";
[mailPicker setMessageBody:emailBody isHTML:NO];
mailPicker.navigationBar.tintColor = [UIColor colorWithRed:0.16 green:0.16 blue:0.16 alpha:1.0];
UIViewController *viewToCreate = [self.delegate viewControllerForPDF:self];
// set attachment file name and subject
if(viewToCreate)
{
if([viewToCreate isKindOfClass:[PDFPlaceOrderFinalizeViewController class]])
{
PDFPlaceOrderFinalizeViewController *pdfViewController = (PDFPlaceOrderFinalizeViewController *)viewToCreate;
if(pdfViewController.showPendingOrderView)
{
fileName = NSLocalizedString(#"Quote.pdf", "PDF");
}
else
{
fileName = NSLocalizedString(#"Order.pdf", "PDF");
}
[mailPicker setSubject:pdfViewController.emailSubject];
}
else if([viewToCreate isKindOfClass:[PDFOrderGuideViewController class]])
{
PDFOrderGuideViewController *pdfViewController = (PDFOrderGuideViewController *)viewToCreate;
fileName = NSLocalizedString(#"OrderGuide.pdf", "PDF");
[mailPicker setSubject:pdfViewController.emailSubject];
}
NSData *data= [self createPDFfromUIView:viewToCreate];
[mailPicker addAttachmentData:data mimeType:#"application/pdf" fileName:fileName];
}
[self presentModalViewController:mailPicker animated:YES];
[[NSNotificationCenter defaultCenter] postNotificationName:kHideBusyIndicatoryEventName object:self];
[self.delegate dismissPopOver];
}
I am developing an app for iOS 7 and used MFMailComposerViewController.
I have tried everything but dismissViewController:withAnimated is not working.
sometimes class automatically call delegate by itself when it first displays viewController using method presentViewCOntroller:withAnimated:completion.
My app is navigation based that's why I think issue is just related with UINavigationController as well.
-(void)sendMail{
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Hello from California!"];
// Set up recipients
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];
// Fill out the email body text
NSMutableString *emailBody =[NSMutableString stringWithString: #"<table border=1 align=\"center\"><tr><th>EventDate</th><th>EventDay</th><th>EventTime</th><th>Speaker</th><th>topic</th></tr>"];
for (int i=0; i<5; i++) {
NSString *eventDate=[NSString stringWithFormat:#"<tr><td>%#</td>",#"12/11"];
NSString *eventDay=[NSString stringWithFormat:#"<td>%#</td>",#"Sunday"];
NSString *eventTime=[NSString stringWithFormat:#"<td>%#</td>",#"12:10 pm"];
NSString *eventSpeaker=[NSString stringWithFormat:#"<td>%#</td>",#"RajVeer"];
NSString *eventTopic=[NSString stringWithFormat:#"<td>%#</td>",#"nano-technology"];
NSString *dataString=[NSString stringWithFormat:#"%#%#%#%#%#</tr>",eventDate,eventDay,eventTime,eventSpeaker,eventTopic];
[emailBody appendString:dataString];
}
NSString *lastTable=#"</table>";
[emailBody appendString:lastTable];
NSLog(#"%#",emailBody);
[picker setMessageBody:emailBody isHTML:YES];
[self presentViewController:picker animated:YES completion:NULL];
}
This should do the trick:
#pragma mark MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
[controller dismissViewControllerAnimated:YES completion:nil];
}
Use this code to present MFMailComposeViewController
[self presentViewController:mailComposerObject animated:YES completion:NULL];
For dismiss MFMailComposeViewController
#pragma mark - MFMailComposeViewControllerDelegate
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult: (MFMailComposeResult)result error:(NSError*)error {
[self dismissViewControllerAnimated:YES completion:NULL];
}
from iOS 6.0 [self presentModalViewController:<#(UIViewController *)#> animated:<#(BOOL)#>] is deprecated.
I have a contact form made of text fields (5 fields) that I would like to send via email to a single email address. How do I do this in xCode?
For anyone stumbling across this question, you can use this drop-in iOS contact form.
This fit my needs well, it uses a PHP component to actually send the email. (an example script is included in the sample project.
I posted it to Github here:
https://github.com/mikecheckDev/MDContactForm
The linked post has a similar answer, but I'm adding my code since it checks for canSendMail already. I also left in a bunch of commented code that makes it easy to add other stuff to the email.
Note that this is substantially easier if you are only targeting iOS 5.
I have a free app, QCount, that uses this code. Indeed, I hope I stripped everything custom from my copy-and-paste :-) http://itunes.apple.com/ng/app/qcount/id480084223?mt=8
Enjoy,
Damien
In your .h:
#import <MessageUI/MessageUI.h>
Methods in your .m:
- (void)emailLabelPressed { // or whatever invokes your email
// Create a mail message in the user's preferred mail client
// by opening a mailto URL. The extended mailto URL format
// is documented by RFC 2368 and is supported by Mail.app
// and other modern mail clients.
//
// This routine's prototype makes it easy to connect it as
// the action of a user interface object in Interface Builder.
Class mailClass = (NSClassFromString(#"MFMailComposeViewController"));
if (mailClass != nil)
{
// We must always check whether the current device is configured for sending emails
if ([mailClass canSendMail])
{
[self displayComposerSheet];
}
else
{
[self launchMailAppOnDevice];
}
}
else
{
[self launchMailAppOnDevice];
}
}
-(void)displayComposerSheet {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Your Form Subject"];
// Take screenshot and attach (optional, obv.)
UIImage *aScreenshot = [self screenshot];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(aScreenshot)];
[picker addAttachmentData:imageData mimeType:#"image/png" fileName:#"screenshot"];
// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:#"first#example.com", nil];
// NSArray *ccRecipients = [[NSArray alloc] init];
// NSArray *bccRecipients = [[NSArray alloc] init];
// NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com", #"third#example.com", nil];
// NSArray *bccRecipients = [NSArray arrayWithObjects:#"fourth#example.com", nil];
[picker setToRecipients:toRecipients];
// [picker setCcRecipients:ccRecipients];
// [picker setBccRecipients:bccRecipients];
// Attach an image to the email.
/* NSString *path = [[NSBundle mainBundle] pathForResource:#"ipodnano"
ofType:#"png"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:#"image/png"
fileName:#"ipodnano"];
*/
// Fill out the email body text.
// NSString *emailBody = #"Use this for fixed content.";
NSMutableString *emailBody = [[NSMutableString alloc] init];
[emailBody setString: #"Feedback"];
// programmatically add your 5 fields of content here.
[picker setMessageBody:emailBody isHTML:NO];
// Present the mail composition interface.
if ([self respondsToSelector:#selector(presentViewController:animated:completion:)]) {
[self presentViewController:picker animated:YES completion:nil];
} else {
[self presentModalViewController:picker animated:YES];
}
}
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error {
if ([self respondsToSelector:#selector(dismissViewControllerAnimated:completion:)]) {
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[self dismissModalViewControllerAnimated:YES];
}
}
-(void)launchMailAppOnDevice {
NSString *recipients = #"mailto:first#example.com?cc=second#example.com,third#example.com&subject=Hello from California!";
NSString *body = #"&body=Feedback";
NSString *email = [NSString stringWithFormat:#"%#%#", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}