从 iOS SDK 发送电子邮件

Sending email from the iOS sdk

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

我们的想法是拥有一个 class SendMessage,所有 classes 都使用它从应用程序内发送电子邮件。它是 NSObject 的子 class 并且是 MFMailComposeViewControllerDelegate

这就是 SendMessage class 的样子

@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

我正在尝试调用 class 使用:

-(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];
    }
}

问题是虽然我能够发送电子邮件,但没有调用委托方法。我该如何解决?

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

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

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

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