How can I send emails from my custom UIActivity class?

643 views Asked by At

I made a costume UIActivity class. I like to send emails with attachments with the class, but I can't send emails, or present any ViewControllers from the class. I am trying to present the Mail ViewController with this:

- (void)prepareWithActivityItems:(NSArray *)activityItems
{
    NSString *subject = [NSString stringWithFormat:@"%@", [self.filePath lastPathComponent]];
    NSString *messageBody = [NSString stringWithFormat:@"%@ was extracted with @FilyForiOS, visit", [self.filePath lastPathComponent]];
        NSData *attachment = [NSData dataWithContentsOfFile:self.filePath];

    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
    mc.mailComposeDelegate = self;
    [mc setSubject:subject];
    [mc setMessageBody:messageBody isHTML:NO];
    [mc setToRecipients:nil];
    [mc addAttachmentData:attachment mimeType:[[self.filePath lastPathComponent] pathExtension] fileName:[self.filePath lastPathComponent]];
    [self presentViewController:mc animated:YES completion:nil]; // Here is the error: No visible @interface for 'MailTo' declares the selector 'presentViewController:animated:completion:'
}

Can anyone tell me how I can present a ViewController from this class?

I used this code: How can I create a custom UIActivity in iOS?

1

There are 1 answers

0
klcjr89 On

Sorry that I'm just now answering this (I know this was asked along time ago) But here is my answer:

#import <MessageUI/MessageUI.h>

@interface EmailActivity : UIActivity <MFMailComposeViewControllerDelegate>

@end

@implementation EmailActivity

- (NSString *)activityTitle
{
    // Your title
    return @"Email";
}

- (UIImage *)activityImage
{
    // Your image
    return [UIImage imageNamed:@"Email"];
}

- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems
{
    return YES;
}

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

- (UIViewController *)activityViewController
{
    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc]init];

    if ([MFMailComposeViewController canSendMail])
    {
        NSString *subject = [NSString stringWithFormat:@"%@", [self.filePath lastPathComponent]];
        NSString *messageBody = [NSString stringWithFormat:@"%@ was extracted with @FilyForiOS, visit", [self.filePath lastPathComponent]];
        NSData *attachment = [NSData dataWithContentsOfFile:self.filePath];

        [mc setSubject:subject];
        [mc setMessageBody:messageBody isHTML:NO];
        [mc setToRecipients:nil];
        [mc addAttachmentData:attachment mimeType:[[self.filePath lastPathComponent] pathExtension] fileName:[self.filePath lastPathComponent]];

        mc.mailComposeDelegate = self;

        return mc;
    }
    else
    {
        return nil;
    }
}

@end