Подтвердить что ты не робот

Цель C: отправлять электронную почту, не выходя из приложения

Как отправить сообщение в приложении, не выходя из приложения.

Это работает:

-(void) sendEmailTo:(NSString *)to withSubject:(NSString *)subject withBody:(NSString *)body {
NSString *mailString = [NSString stringWithFormat:@"mailto:?to=%@&subject=%@&body=%@",
                        [to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
                        [subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
                        [body stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailString]];
}

но отправляется в почтовое приложение для отправки. Есть ли способ сделать это, не выходя из приложения?

4b9b3361

Ответ 1

Да. Используйте MFMailComposeViewController.

// From within your active view controller
if([MFMailComposeViewController canSendMail]) {
    MFMailComposeViewController *mailCont = [[MFMailComposeViewController alloc] init];
    mailCont.mailComposeDelegate = self;

    [mailCont setSubject:@"yo!"];
    [mailCont setToRecipients:[NSArray arrayWithObject:@"[email protected]"]];
    [mailCont setMessageBody:@"Don't ever want to give you up" isHTML:NO];

    [self presentModalViewController:mailCont animated:YES];
    [mailCont release];
}


// Then implement the delegate method
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    [self dismissModalViewControllerAnimated:YES];
}

Ответ 2

  • Добавить структуру MessageUI:

    • Нажмите на проект
    • Выберите "Сформировать фазы"
    • Разверните ссылку "Связывание двоичных файлов с библиотеками"
    • Нажмите "+" и введите "Сообщение", чтобы найти фреймворк "MessageUI", затем добавьте.
  • В текущем контроллере представления добавьте импорт и выполните протокол:

    #import <MessageUI/MessageUI.h> 
    #import <MessageUI/MFMailComposeViewController.h> 
    @interface MyViewController : UIViewController<MFMailComposeViewControllerDelegate>
    

Добавить методы:

    -(void)sendEmail {
        // From within your active view controller
        if([MFMailComposeViewController canSendMail]) {
            MFMailComposeViewController *mailCont = [[MFMailComposeViewController alloc] init];
            mailCont.mailComposeDelegate = self;        // Required to invoke mailComposeController when send

            [mailCont setSubject:@"Email subject"];
            [mailCont setToRecipients:[NSArray arrayWithObject:@"[email protected]"]];
            [mailCont setMessageBody:@"Email message" isHTML:NO];

            [self presentViewController:mailCont animated:YES completion:nil];
        }
    }

    - (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
        [controller dismissViewControllerAnimated:YES completion:nil];
    }

Ответ 3

Обновлено для iOS 6. Обратите внимание, что это использует ARC и не использует устаревшее представление модального представления:

#import <MessageUI/MessageUI.h> 
#import <MessageUI/MFMailComposeViewController.h> 
@interface MyViewController : UIViewController<MFMailComposeViewControllerDelegate>

И затем код для отображения экрана электронной почты:

- (IBAction)emailButtonPushed:(id)sender {

    if([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *mailCont = [[MFMailComposeViewController alloc] init];
        mailCont.mailComposeDelegate = self;
        [mailCont setSubject:@"Your email"];
        [mailCont setMessageBody:[@"Your body for this message is " stringByAppendingString:@" this is awesome"] isHTML:NO];
        [self presentViewController:mailCont animated:YES completion:nil];
    }

}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    //handle any error
    [controller dismissViewControllerAnimated:YES completion:nil];
}