0

我注意到我多次使用邮件功能,所以我决定为重复多次的函数创建一个独立的类,而不是多次复制粘贴代码

类调用成功,邮件函数调用成功,但是调用函数后手机邮件客户端没有出现

这是我的代码

在主类中,我执行以下调用

-(void)emailFunction{
...

CommonlyUsed Email = [[CommonlyUsed alloc] init];
[Email sendMail:receipient :CC :BCC :subject :body];

...
}

在我的 CommonUsed.h 中,我有以下 IDE:

#import <UIKit/UIKit.h>
#import <MessageUI/MFMailComposeViewController.h>
#import <MessageUI/MessageUI.h>


@interface CommonlyUsed : UIViewController <MFMailComposeViewControllerDelegate>{

在 CommonUsed.m 我有以下内容:

-(void)sendMail:(NSString*)receipient:(NSString*)cc:(NSString*)bcc:(NSString*)subject:(NSString*)body{

 MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init];
    [ composer setMailComposeDelegate:self];

 if ( [MFMailComposeViewController canSendMail]){
if (receipient) {
            [composer setToRecipients:[NSArray arrayWithObjects:receipient, nil]];
        }

        if (cc) {
            [composer setCcRecipients:[NSArray arrayWithObjects:receipient, nil]];
        }

        if (bcc) {
            [composer setBccRecipients:[NSArray arrayWithObjects:receipient, nil]];
        }

        if (subject) {
             [composer setSubject:subject];
        }

 [composer setMessageBody:body isHTML:HTMLBody];

        [composer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];

        [self presentModalViewController:composer animated:YES];
        }
}

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    if(error){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"error" message:[NSString stringWithFormat:@"error %@", [error description]] delegate:nil cancelButtonTitle:@"dismiss" otherButtonTitles:nil, nil];
        [alert show];
        [self dismissModalViewControllerAnimated:YES];
    }
    else{
        [self dismissModalViewControllerAnimated:YES];
    }

    }

代码编译并运行没有错误我错过了什么?

4

2 回答 2

2

您发送presentModalViewController:到您Email的 class实例CommonlyUsed,但此实例不是视图层次结构中的视图控制器。

您必须发送presentModalViewController:到当前活动的视图控制器。

于 2012-08-09T18:53:22.797 回答
2

而不是这样做:

[self presentModalViewController:composer animated:YES];

做这个:

[[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentModalViewController:composer animated:YES];

或这个:

[[[[UIApplication sharedApplication] keyWindow] rootViewController] presentModalViewController:composer animated:YES];

您的电子邮件类当前不是活动视图控制器,因此它无法呈现模式视图控制器,您需要使用活动视图控制器,例如主 UIWindow 的 rootViewController。

编辑

如果您在 emailClient 被解除时使用 ARC,则您的对象(委托)将从内存中删除,因此解决方案是将 CommonlyUsed 类设为 Singleton:

+(CommonlyUsed *)sharedInstance {

    static CommonlyUsed * cu = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        cu = [[CommonlyUsed alloc] init];

    });

    return cu;
}

所以你会这样使用它:

CommonlyUsed * email = [CommonlyUsed sharedInstance];
[email sendMail:receipient :CC :BCC :subject :body];
于 2012-08-09T19:11:32.807 回答