我正在尝试从我的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];
}
}
问题是虽然我能够发送电子邮件,但是没有调用委托方法。我该如何解决?
答案 0 :(得分:1)
您的代理人是UIViewController
,因此请在那里实施mailComposeController:didFinishWithResult:error
委托方法。
答案 1 :(得分:0)
我认为问题是您的对象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
必须设为自我