Отображать предупреждающее сообщение об успехе при отправке почты из MFMailComposeViewController в iPhone - PullRequest
4 голосов
/ 05 декабря 2011

Мне нужно отобразить предупреждающее сообщение, когда пользователь успешно отправляет почту с iPhone с помощью MFMailComposeViewController.

Я пытался использовать делегат didFinishWithResult, но он вызывает отправку и отмену, и как мы можем определить, успешно ли мы отправили сообщение?

Ответы [ 5 ]

12 голосов
/ 05 декабря 2011
Try this code

-(IBAction)Btn_EmailPressed:(id)sender{
    if (![MFMailComposeViewController canSendMail]) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Alert" message:@"Email cannot be configure." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }else {
        picker = [[MFMailComposeViewController alloc] init];
        picker.mailComposeDelegate=self;
        [picker setToRecipients:nil];
                [picker setSubject:@"Email"];
                [picker setMessageBody:nil isHTML:NO];
                NSArray *toRecipients = [[NSArray alloc] initWithObjects:lblSite.text,nil];
                [picker setToRecipients:toRecipients];
                [self presentModalViewController:picker animated:YES];
            }
}


- (void)mailComposeController:(MFMailComposeViewController*)mailController didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    NSString *msg1;
    switch (result)
    {
        case MFMailComposeResultCancelled:
            msg1 =@"Sending Mail is cancelled";
            break;
        case MFMailComposeResultSaved:
            msg1=@"Sending Mail is Saved";
            break;
        case MFMailComposeResultSent:
            msg1 =@"Your Mail has been sent successfully";
            break;
        case MFMailComposeResultFailed:
            msg1 =@"Message sending failed";
            break;
        default:
            msg1 =@"Your Mail is not Sent";
            break;
    }
    UIAlertView *mailResuletAlert = [[UIAlertView alloc]initWithFrame:CGRectMake(10, 170, 300, 120)];
    mailResuletAlert.message=msg1;
    mailResuletAlert.title=@"Message";
    [mailResuletAlert addButtonWithTitle:@"OK"];
    [mailResuletAlert show];
    [mailResuletAlert release];
    [self dismissModalViewControllerAnimated:YES];  
}
2 голосов
/ 16 февраля 2012

У меня были проблемы с этим подходом.В моем приложении я использовал MFMailComposeViewController для электронной почты и MFMessageComposeViewController для SMS-сообщений, и обе процедуры didFinishWithResult использовали аналогичный подход, описанный выше, где перед выводом VC отображается предупреждение.

Казалось, что если вы отправилиSMS, в следующий раз, когда вы попробуете отправить электронное письмо, курсор не появится в теле письма, и вы не сможете выделить текст.Также в отладчике я получал «wait_fences: не удалось получить ответ: 10004003».

В конце концов я просто удалил представления предупреждений из этой части приложения, и проблема исчезла.Если у кого-то есть решение по этому вопросу, я буду рад его услышать.

1 голос
/ 12 декабря 2017

Быстрая версия ответа.

       func sendMail(){
                if MFMailComposeViewController.canSendMail() {
                    let mail = MFMailComposeViewController()
                    mail.mailComposeDelegate = self
                    mail.setToRecipients(["hello@gmail.com"])
                    present(mail, animated: true)
                } else {
                    showSendMailErrorAlert()
                }
            }

        func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
            switch result {
                case .cancelled: print("Sending Mail is cancelled")
                case .sent : print("Your Mail has been sent successfully")
                case .saved : print("Sending Mail is Saved")
                case .failed : print("Message sending failed")
            }
            controller.dismiss(animated: true, completion: nil)
        }

        func showSendMailErrorAlert() {
            showAlert(title: "Could Not Send Email", message: "Your device could not send e-mail.  Please check e-mail configuration and try again.")
        }
1 голос
/ 05 декабря 2011
(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error

Используйте этот делегат, и внутри этого MFMailComposeResult есть enum

enum MFMailComposeResult {
   MFMailComposeResultCancelled,
   MFMailComposeResultSaved,
   MFMailComposeResultSent,
   MFMailComposeResultFailed
};
typedef enum MFMailComposeResult MFMailComposeResult;
1 голос
/ 05 декабря 2011

вы должны реализовать этот метод для объекта делегата ...

– mailComposeController:didFinishWithResult:error:

посмотрите на это подробнее ... http://developer.apple.com/library/ios/#documentation/MessageUI/Reference/MFMailComposeViewControllerDelegate_protocol/Reference/Reference.html#//apple_ref/occ/intf/MFMailComposeViewControllerDelegate

...