从iOS sdk发送电子邮件



我正在尝试从我的iOS应用程序中发送电子邮件。

这个想法是有一个类SendMessage,所有类都使用它从应用程序中发送电子邮件。它是NSObject的一个子类,是MFMailComposeViewControllerDelegate

这就是SendMessage类的

@implementation SendMessage
- (void) sendEmailFromViewController : (UIViewController *)viewController withSubject : (NSString *) subject withRecipient : (NSString *)recipient withMessage : (NSString *)message withCompletionBlock : (void(^)(void))completionBlock withFailure : (void(^)(void))failure {
    self.viewController = viewController;
    if (![MFMailComposeViewController canSendMail]){
        if (failure)
            failure();
    }
    else {
        MFMailComposeViewController *messageController = [[MFMailComposeViewController alloc] init];
        messageController.mailComposeDelegate = self.viewController;
        [messageController setSubject:subject];
        [messageController setToRecipients:[NSArray arrayWithObject:recipient]];
        [messageController setMessageBody:message isHTML:NO];
        [self.viewController presentModalViewController:messageController animated:YES];
    }
}
-(void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    [self.viewController dismissViewControllerAnimated:YES completion:nil];
}
@end

我正在尝试使用调用该类

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 3) {
        SendMessage *sendFeedback = [[SendMessage alloc] init];
        [sendFeedback sendEmailFromViewController:self withSubject:@"App Feedback" withRecipient:@"ashisha@moj.io" withMessage:@"This is app feedback" withCompletionBlock:nil withFailure:nil];
    }
}

问题是,尽管我可以发送电子邮件,但没有调用delegate方法。我该如何修复它?

您的委托是UIViewController,因此在那里实现mailComposeController:didFinishWithResult:error委托方法。

我认为问题在于您的对象sendFeedback在块的末尾被释放。

最好的解决方案是创建singleton对象,然后使用它

SendMessage.h文件中添加

+ (instancetype) sharedManager;

SendMessage.m文件中添加

+ (instancetype) sharedManager{
    static SendMessage* instance = nil;
    if(!instance){
        instance = [[SendMessage alloc] init];
    }
    return instance;
}

您可以在代码中的任何位置使用单例

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 3) {
        SendMessage *sendFeedback = [SendMessage sharedManager];
        [sendFeedback sendEmailFromViewController:self withSubject:@"App Feedback" withRecipient:@"ashisha@moj.io" withMessage:@"This is app feedback" withCompletionBlock:nil withFailure:nil];
    }
}

此外,messageController.mailComposeDelegate必须设置为self

最新更新