如何使用setMessageBody将NSString添加到电子邮件中

时间:2012-09-05 18:04:39

标签: objective-c cocoa ios5 nsstring mfmailcomposeviewcontroller

我对iOS很新,所以如果我特别密集的话,请跟我一起玩。我正在构建我的第一个应用程序的最后阶段,我正在尝试实现自动填充的电子邮件。我已经在一个单独的测试环境中正确地弹出了emailviewcontroller,但是我无法弄清楚如何在消息体中添加字符串。基本上我在gui的根控制器上有三个按钮,用于设置三个字符串的值。我想要的只是在消息体中重现这三个字符串(如果可能的话用逗号分隔)。到目前为止,这是我的代码。任何帮助将不胜感激。感谢

    -(IBAction)displayComposerSheet
    {

    NSArray *recipient = [NSArray arrayWithObjects:@"testemail@office.co.uk", nil];

    if([MFMailComposeViewController canSendMail])
    {
            MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc]             init];
        mailViewController.mailComposeDelegate = self;
        [mailViewController setSubject:@"Place holder ... this is a test subject"];
        [mailViewController setMessageBody: isHTML:NO];
        [mailViewController setToRecipients:recipient];


        [self presentModalViewController:mailViewController animated:YES];
    }
    else
        NSLog(@"Device is unable to send email in its current state");

    }

    -(void)mailComposeController:(MFMailComposeViewController *)controller     didFinishWithREsult:(MFMailComposeResult)result error:(NSError *)error
{
    [self dismissModalViewControllerAnimated:YES];
}
- (IBAction)addString1:(id)sender {

    NSString *string1;
    string1 = @"teststring1";

}

- (IBAction)addString2:(id)sender {

    NSString *string2;
    string2 = @"teststring2";
}

- (IBAction)addString3:(id)sender {
    NSString *string3;
    string3 = @"teststring3";
}

1 个答案:

答案 0 :(得分:1)

首先,您需要在.h文件中声明字符串,以便在整个.m中使用它们

@interface ViewController : UIViewController
{
    NSString *string1;
    NSString *string2;
    NSString *string3;
}

然后在邮件编辑器中,您将使用格式化字符串按顺序显示字符串(由%@转义)

    [mailViewController setMessageBody:[NSString stringWithFormat:@"%@, %@, %@",string1,string2,string3] isHTML:NO];

当然,在头文件中声明字符串之后,不需要在本地声明它们,所以将IBActions更改为:

   - (IBAction)addString1:(id)sender 
    {
        string1 = @"teststring1";
    }

    - (IBAction)addString2:(id)sender 
    {
        string2 = @"teststring2";
    }

    - (IBAction)addString3:(id)sender 
    {
        string3 = @"teststring3";
    }

此外,为了避免将不需要的(null)实例插入到邮件正文中,我建议您在viewDidLoad中为这些字符串指定一个初始空白值。这样一来,会在没有任何内容的情况下开始,但它们不会是零。

- (void)viewDidLoad
{
    [super viewDidLoad];
    string1 = @"";
    string2 = @"";
    string3 = @"";
}