【发布时间】:2015-05-08 01:28:18
【问题描述】:
我正在用非常简单的方法发送电子邮件
#import <MessageUI/MFMailComposeViewController.h>
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMessageComposeViewController.h>
-(void) sendEmailto: (NSArray*)p_recipient withSubject:(NSString*)p_subject body:(NSString*)p_body andAttachment:(NSData*)p_attachment
{
MFMailComposeViewController *emailComposer = [[MFMailComposeViewController alloc] init];
emailComposer.mailComposeDelegate = self;
if ([MFMailComposeViewController canSendMail] == YES)
{
[emailComposer setSubject:p_subject];
if(p_recipient != nil)
{
[emailComposer setToRecipients:p_recipient];
}
if (p_body!= nil && [p_body isEqualToString:@""]==NO)
{
[emailComposer setMessageBody:p_body isHTML:NO];
}
if(p_attachment != nil)
{
[emailComposer addAttachmentData:p_attachment mimeType:@"image/jpeg" fileName:@"image.jpg"];
}
// Present mail view controller on screen
[emailComposer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentModalViewController:emailComposer animated:YES];
self.sentEmailTargetController = p_target;
}
else
{
NSLog(@"Can't Open Email");
}
}
- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(@"e-mail cancelled");
break;
case MFMailComposeResultSaved:
NSLog(@"e-mail saved");
break;
case MFMailComposeResultSent:
NSLog(@"e-mail sent");
break;
case MFMailComposeResultFailed:
NSLog(@"e-mail sent failure: %@", [error localizedDescription]);
break;
default:
break;
}
if (![[self presentedViewController] isBeingDismissed])
{
[self dismissViewControllerAnimated:YES completion:NULL];
}
}
我在界面中有声明的MFMailComposeViewControllerDelegate委托
在我的设备上运行它,电子邮件控制台打开,我可以写一条消息,单击发送关闭电子邮件窗口,但实际上并没有发送电子邮件。 - (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error 方法记录已发送的电子邮件,但邮件未到达目的地。尝试了几个电子邮件帐户。
【问题讨论】:
-
仅供参考 - 不要检查
BOOL值与YES或NO。将if (someBool == YES)更改为简单的if (someBool)。并将if (someBool == NO)更改为if (!someBool)(注意!)。 -
@rmaddy 每个编码员都有自己的编码风格,你的评论就像告诉我不要在自己的行中写 { 并将其放在代码行的末尾...
-
其实我的评论不是基于风格,而是基于实际功能。直接比较
NO和YES实际上会导致代码无法按预期工作。在大多数情况下,它可能会起作用,但在某些情况下,它可能会失败,而且这将是一个非常难以追踪的错误。 -
@liva 听听你被告知的内容。试着记住你是提出问题的人;这意味着你不知道。 rmaddy 告诉你的是至关重要的。这不是风格问题。您的代码错误,很容易导致错误的结果。
canSendMail(或任何 BOOL)可以为真,但不等于 YES。从不、从不、从不将 BOOL 与 YES 或 NO 进行比较;只需直接使用 BOOL 作为条件。 -
@matt 我确实删除了与 YES 的比较,NO 它仍然不起作用!它确实将其记录为已发送
标签: ios email mfmailcomposeviewcontroller